SpringMVC統一轉換null值爲空字符串的方法

在SpringMVC中,能夠經過在<mvc:annotation-driven>中配置<mvc:message-converters>,把null值統一轉換爲空字符串,解決這個問題。下面以JSon交互的方式爲例說明如何實現:java

第一步:建立一個ObjectMapperspring

package com.xjj.anes.mvc.converter;  
  
import java.io.IOException;  
  
import com.fasterxml.jackson.core.JsonGenerator;  
import com.fasterxml.jackson.core.JsonProcessingException;  
import com.fasterxml.jackson.databind.JsonSerializer;  
import com.fasterxml.jackson.databind.ObjectMapper;  
import com.fasterxml.jackson.databind.SerializerProvider;  
  
/** 
 * @description: 轉換null對象爲空字符串 
 */  
public class JsonObjectMapper extends ObjectMapper {  
    private static final long serialVersionUID = 1L;  
  
    public JsonObjectMapper() {  
        super();  
        // 空值處理爲空串  
        this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {  
            @Override  
            public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {  
                jg.writeString("");  
            }  
        });  
    }  
}  

  第二步:在SpringMVC配置文件中,把新建的ObjectMapper注入給MappingJackson2HttpMessageConverterjson

<!-- 註冊RequestMappingHandlerMapping 和RequestMappingHandlerAdapter 兩個bean。-->  
<mvc:annotation-driven>  
    <mvc:message-converters>  
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
            <property name="objectMapper">  
                <bean class="com.xjj.anes.mvc.converter.JsonObjectMapper"></bean>  
            </property>  
        </bean>  
    </mvc:message-converters>  
</mvc:annotation-driven>  
相關文章
相關標籤/搜索