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

时间:2022-03-31 16:04:31

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

第一步:创建一个ObjectMapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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

1
2
3
4
5
6
7
8
9
10
<!-- 注册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>