在springMvc控制器中,返回對象給前端的時候,前端可能會要求給數字類型的字段加雙引號,日期格式的轉化,不但願返回null等狀況,能夠採用springMvc的轉化器進行實現,具體配置以下:前端
1.在springMvc配置文件中加入以下配置:ObjectMappingCustomer是一個自定義轉化器,須要實現ObjectMapper接口java
<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接口spring
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.配置先後效果對比:json
配置前:mvc
配置後:app