SpringMVC Jackson为null转化为空串处理

版权声明: https://blog.csdn.net/Dongguabai/article/details/83186335
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;

import java.io.IOException;

/**
 * @author Dongguabai
 * @date 2018/10/19 17:13
 */
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配置文件:

 <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
        <property name="objectMapper">
            <bean class="com.api.framwork.converter.JsonObjectMapper"/>
        </property>
    </bean>

其实这里方法有很多,可以自行扩展:

参考资料:

https://www.cnblogs.com/cvst/p/5993646.html

猜你喜欢

转载自blog.csdn.net/Dongguabai/article/details/83186335
今日推荐