springboot返回给前端数据将null值转化为对应的空字符串、空数组、时间统一格式化等等

本文介绍如何在SpringBoot项目中使用FastJson替代默认的Jackson作为JSON消息转换器,并详细解释了FastJson配置项及为何要将其设置为优先级最高的转换器。

实现WebMvcConfigurer

代码如下:

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class MvcConfig implements WebMvcConfigurer {


  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

    FastJsonConfig fastJsonConfig = new FastJsonConfig();

    fastJsonConfig.setSerializerFeatures(

            SerializerFeature.WriteNullStringAsEmpty,                        // 将String类型的字段如果为null,输出为"",而非null

//            SerializerFeature.WriteNullNumberAsZero,                         // 将Number类型的字段如果为null,输出为0,而非null

            SerializerFeature.WriteNullListAsEmpty,                          // 将List类型的字段如果为null,输出为[],而非null

//            SerializerFeature.WriteNullBooleanAsFalse,                      // 将Boolean类型的字段如果为null,输出为false,而非null

            SerializerFeature.DisableCircularReferenceDetect                // 避免循环引用

    );

    fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");                   // 全局时间格式化为yyyy-MM-dd HH:mm:ss

    fastConverter.setFastJsonConfig(fastJsonConfig);

    converters.add(0, fastConverter);                                    // 为什么加0,详情见:https://www.xttblog.com/?p=5165

  }

}

此时默认的消息转换器已经失效了,springboot默认的Jackson也是失效了(如果这个A类里面还有一个B类,这个B类是A类的一个属性,那么无法判断B类的属性)

为什么加0,详情见:https://www.xttblog.com/?p=5165  如果打不开见下面截图,我已经截图保存了

 

这里还有其他人写的也不错

https://blog.youkuaiyun.com/qq_38132283/article/details/89339817

如果网页打不开, 可以查看下面的截图

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值