当使用com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter转换返回数据为json时,会省略掉为空为null的属性值。
解决办法在sping-mvc.xml配置json转换器时加上对空和null的处理,配置如下:
- <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="features">
- <array>
- <value>QuoteFieldNames</value>
- <value>WriteDateUseDateFormat</value>
- <!-- 将Collection类型字段的字段空值输出为[] -->
- <value>WriteNullListAsEmpty</value>
- <!-- 将字符串类型字段的空值输出为空字符串 "" -->
- <value>WriteNullStringAsEmpty</value>
- <!-- 将Boolean类型字段的空值输出为false -->
- <value>WriteNullBooleanAsFalse</value>
- </array>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
网上大神是这样解释,豁然开朗。
我这边是这样配置的:
<!-- 设置jackson忽略null -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>