zoukankan      html  css  js  c++  java
  • SpringMVC统一转换null值为空字符串的方法 !

     

    在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> 
  • 相关阅读:
    Binary Stirling Numbers
    Count the Buildings ( s1 )
    P3375 【模板】KMP字符串匹配
    POJ2151Check the difficulty of problems
    fbx 模型转换 export
    Linux --windows vs
    phyreengine 3.12.0 安装遇到的问题
    A trip through the graphics pipeline 2011 Part 10(翻译)
    服务端 unity
    nsight 使用问题
  • 原文地址:https://www.cnblogs.com/erfsfj-dbc/p/9948550.html
Copyright © 2011-2022 走看看