SpringMVC统一转换null值为空字符串的方法

在SpringMVC中,可以通过在<mvc:annotation-driven>中配置<mvc:message-converters>,把null值统一转换为空字符串,解决这个问题。下面以JSon交互的方式为例说明如何实现:

第一步:创建一个ObjectMapper

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注入给MappingJackson2HttpMessageConverter

<!-- 注册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>  

  

posted @ 2016-10-24 16:57  大神不解释  阅读(15550)  评论(0编辑  收藏  举报