背景:fastjson默认会过滤对象中属性为null值
问题:下面的配置没有将对象属性为null的值过滤
<bean name="fastJsonConfig" class="com.alibaba.fastjson.support.config.FastJsonConfig">
<property name="serializerFeatures">
<array>
<!--输出key时是否使用双引号,默认为true-->
<value>QuoteFieldNames</value>
<!--全局修改日期格式-->
<value>WriteDateUseDateFormat</value>
<!--按照toString方式获取对象字面值-->
<value>WriteNonStringValueAsString</value>
<!-- 字段如果为null,输出为"",而非null -->
<value>WriteNullStringAsEmpty</value>
</array>
</property>
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<description>JSON转换器</description>
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<property name="fastJsonConfig" ref="fastJsonConfig"></property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
原因: FastJsonConfig中配置了<value>WriteNullStringAsEmpty</value>属性,会Object、Date类型值默认会将以null,类型输出,字符串会展示成""
影响:如果是做前后端分离,大量null值属性,回传到客户端,浪费客户端流量,也影响性能
处理方式: FastJsonConfig中去除<value>WriteNullStringAsEmpty</value>属性,部分你不需要显示的属性使用@JSONField(serialize = false)注解
fastjson方式springboot方式配置
@Configuration
public class FastJsonConverterConfig {
@Bean
public HttpMessageConverters customConverters() {
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNonStringValueAsString);
FastJsonHttpMessageConverter fastJson = new FastJsonHttpMessageConverter();
fastJson.setFastJsonConfig(fastJsonConfig);
List<MediaType> mediaTypeList = new ArrayList<>();
mediaTypeList.add(MediaType.valueOf("application/json;charset=UTF-8"));
mediaTypeList.add(MediaType.valueOf("text/html;charset=UTF-8"));
fastJson.setSupportedMediaTypes(mediaTypeList);
return new HttpMessageConverters(fastJson);
}
}

4004

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



