FastJsonHttpMessageConverter使用中问题

背景: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);
    }
}

转载于:https://my.oschina.net/u/1017791/blog/2874132

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值