SpringBoot01-- 默认Jackson和fastJson的Json转化器对null处理对比

       前言:在实际项目中,我们难免会遇到一些 null 值的出现,我们转 JSON 时,不希望这些 null 出现,比如我们期望所有的 null 在转 JSON 时都变成 "" 这种空字符串 我们这里使用默认Jackson和fastJson的Json转化器对null处理做一个对比

1.默认Jackson的JSON转化器对null的处理

写一个JacksonConfig配置类

package com.itcodai.course01.configuration;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * 使用Jackon作为JSON MessageConverter
 * 对null处理为""
 *
 * @author XuHao
 * Email [email protected]
 * create on 2018/7/29
 */

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

写一个Controller里写一个如下的测试方法

@RequestMapping(value = "/map", method = RequestMethod.GET)
    public Map<String, Object> getMap() {
        Map<String, Object> map = new HashMap<>(3);
        User user = new User(1, "徐浩", null);
        map.put("作者信息", user);
        map.put("博客地址", "http://blog.itcodai.com");
        map.put("CSDN地址", null);
        map.put("粉丝数量", 1);
        return map;
    }

使用Postman测试返回来的结果,如下,这里将null都处理成了""

2.使用fastJson的JSON转化器处理对null的处理

写一个FastJsonConfig配置类

package com.itcodai.course01.configuration;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用阿里 fastjson 作为JSON MessageConverter
 * 使用 fastjson 时,对 null 的处理和 Jackson 有些不同,
 * 需要继承 WebMvcConfigurationSupport 类,
 * 然后覆盖 configureMessageConverters 方法
 *
 * @author XuHao
 * Email [email protected]
 * create on 2018/7/29
 */

@Configuration
public class FastJsonConfigo extends WebMvcConfigurationSupport {

    /**
     * 使用阿里 fastjson 作为JSON MessageConverter
     *
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                //保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的NULL转化为""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的NULL转化为0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的NULL转成[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的NULL转化为false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }

}

同样使用Postman测试同一个方法结果如下:

这里就可以看出fastJson的局限性,没有一个Object处理为""的设置

这里给出两种json工具的比较,在实际开发中根据需求选择

猜你喜欢

转载自blog.csdn.net/PORSCHE_GT3RS/article/details/81276797