首页   >   代码编程   >   JAVA开发

spring框架返回json数据null转空字符串

spring项目中,前端获取服务器返回的json时,里面有null值,如果没做校验,就会导致js报错,但是不推荐每个返回的地方手动处理,而是应该在框架中统一配置。

前面关于json日期格式化的文章中,提到了spring默认使用的是jackson来做json序列化,相对应的converter是MappingJackson2HttpMessageConverter,我们依旧还是要利用它提供的ObjectMapper来解决上面的问题。

1、继承ObjectMapper,自定义mapper

package com.ssm.common;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * SpringMVC中@ResponseBody返回json时,默认使用jackson,但是不会自动将null转成空字符串,
 * 所以这里继承ObjectMapper重写构造方法,在构造方法中进行手动处理
 * Created by SongFei on 2016/12/26.
 */
public class JsonMapper extends ObjectMapper {

    public JsonMapper() {

        super();

        // null值转空字符串
        this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator generator, SerializerProvider provider) throws IOException {
                generator.writeString("");
            }
        });

        // 不返回时间戳格式
        this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // 遇到不认识的字段,不抛异常
        this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 指定自己想要的日期格式,如:yyyy-MM-dd HH:mm:ss
        this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    }

}

2、在配置文件中的<mvc:annotation-driven/>标签中对messageconverter做特殊处理,引入自定义的ObjectMapper

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                    <value>text/json;charset=UTF-8</value>
                </list>
            </property>
            <!--引入自定义的ObjectMapper-->
            <property name="objectMapper">
                <bean class="com.ssm.common.JsonMapper"/>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

上述两个步骤确认无误之后,看一下效果:

spring框架返回json数据null转空字符串

如果是springboot项目,就更简单了,直接在config类中对ObjectMapper操作,都不用自己重新写:

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    List<MediaType> supported = new ArrayList<>();
    supported.add(MediaType.APPLICATION_JSON_UTF8);
    mappingJackson2HttpMessageConverter.setSupportedMediaTypes(supported);

    // JsonMapper
    ObjectMapper objectMapper = new ObjectMapper();

    // null值的处理,必须要放在第一步,否则会将下面的日期格式化覆盖掉
    // null ==> ""
    objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString("");
        }
    });

    // 处理默认日期格式化:yyyy-MM-dd HH:mm:ss
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setDateFormat(new SimpleDateFormat(Constants.TIME_PATTERN));
    
    mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
    return mappingJackson2HttpMessageConverter;
}

QQ群: 686430774

站长Q: 1347384268

分享到:

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

欢迎分享本文,转载请注明出处!

作者:不忘初心

发布时间:2019-05-31

永久地址:https://www.jiweichengzhu.com/article/225600001e034f2691345ac14673b108

评论