在项目开发中经常需要讲后台的某个对象以json的方式传递给前台,默认配置将为空的属性不传递给前台。
<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>
这样容易造成同一个属性在前台有的显示undefined,有的显示真实值。
为了防止前台在数据为空时显示undefined,可采用以下方法:
使用jackson库的注解:@JsonInclude(Include.ALWAYS) 。
将该注解放在属性上,表示如果该属性不管是不是为NULL都将参与序列化。
放在类上面,那对这个类的全部属性起作用。
Include.ALWAYS 属性都序列化
Include.NON_DEFAULT 属性为默认值不序列化
Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
Include.NON_NULL 属性为NULL 不序列化