FastJsonHttpMessageConverter使用中问题

背景:fastjson默认会过滤对象中属性为null值   html

问题:下面的配置没有将对象属性为null的值过滤spring

<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>json

    <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,类型输出,字符串会展现成""springboot

影响:若是是作先后端分离,大量null值属性,回传到客户端,浪费客户端流量,也影响性能mvc

处理方式: FastJsonConfig中去除<value>WriteNullStringAsEmpty</value>属性,部分你不须要显示的属性使用@JSONField(serialize = false)注解app

 

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);
    }
}
相关文章
相关标签/搜索