在spring-servlet.xml中配置json的转换器:
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!-- objectMapper配置 -->
<property name="objectMapper">
<bean class="com.test.MyObjectMapper" />
<!-- <bean class="com.fasterxml.jackson.databind.ObjectMapper">
驼峰命名法转换为小写加下划线
<property name="propertyNamingStrategy">
<bean class="com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy" />
</property>
为null字段时不输出
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
禁用空对象转换json校验
<property name="configure">
<value type="com.fasterxml.jackson.databind.SerializationFeature">FAIL_ON_EMPTY_BEANS</value>
</property>
忽略未知的字段
<property name="configure">
<value type="com.fasterxml.jackson.databind.DeserializationFeature">FAIL_ON_UNKNOWN_PROPERTIES</value>
</property>
</bean> -->
</property>
<!-- 支持的类型,编码 -->
<property name="supportedMediaTypes">
<span style="white-space:pre"> </span><list>
<span style="white-space:pre"> </span><value>application/json;charset=UTF-8</value>
</list>
<span style="white-space:pre"> </span></property>
</bean>
MyObjectMapper.java文件如下:
public class MyObjectMapper extends ObjectMapper {
private static final long serialVersionUID = 4402127997078513582L;
public MyObjectMapper() {
//设置null值不参与序列化(字段不被显示)
this.setSerializationInclusion(Include.NON_NULL);
// 禁用空对象转换json校验
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//驼峰命名法转换为小写加下划线
this.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
}