实现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
如果网页打不开, 可以查看下面的截图

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

被折叠的 条评论
为什么被折叠?



