在springMvc控制器中,返回对象给前端的时候,前端可能会要求给数字类型的字段加双引号,日期格式的转化,不希望返回null等情况,可以采用springMvc的转化器进行实现,具体配置如下:
1.在springMvc配置文件中加入如下配置:ObjectMappingCustomer是一个自定义转化器,需要实现ObjectMapper接口
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.lantaiyuan.ebus.custom.util.ObjectMappingCustomer"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
2.新建一个ObjectMappingCustomer去实现ObjectMapper接口
package com.lantaiyuan.ebus.custom.util;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.core.JsonProcessingException;
public class ObjectMappingCustomer extends ObjectMapper {
/**
*
*/
private static final long serialVersionUID = -6401263387943827254L;
public ObjectMappingCustomer() {
super();
// 数字也加引号
this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);
//以下方法是将返回的json对象中的null替换为“”,如果需要替换成其他信息,可以在这边自定义
this.getSerializerProvider().setNullValueSerializer(new com.fasterxml.jackson.databind.JsonSerializer<Object>() {
@Override
public void serialize(Object arg0, JsonGenerator jg, SerializerProvider arg2)
throws IOException, JsonProcessingException {
jg.writeString("");
}
});
}
}
3.配置前后效果对比:
配置前:
配置后: