SpringMVC配置JSON转换器,如果字段为空,则不输出,配置如下:
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<!-- 时间格式转换 -->
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</property>
<!-- 为null字段时不转换 -->
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
<!-- <bean class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField" value="com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL" />
</bean> -->
</property>
</bean>
</property>
</bean>
但是启动时,一直报错,错误如下:
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'serializationInclusion' of bean class [com.fasterxml.jackson.databind.ObjectMapper]: Bean property 'serializationInclusion' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1024)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:900)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 61 more
------解决思路----------------------
serializationInclusion 这个不是有问题么?~

------解决思路----------------------
在需要序列化为json输出的类上增加
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)