springboot中返回值json中null转换空字符串
在实际项⽬中,我们难免会遇到⼀些⽆值。当我们转JSON时,不希望这些null出现,⽐如我们期望所有的null在转JSON时都变成“”“”这种空字符串,那怎么做呢?
Jackson中对null的处理
1 @Configuration
2public class JacksonConfig {
3    @Bean
4    @Primary
5    @ConditionalOnMissingBean(ObjectMapper.class)
6public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
7        ObjectMapper objectMapper = ateXmlMapper(false).build();
8        SerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
9            @Override
10public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
11                jsonGenerator.writeString("");
12            }
13        });
14return objectMapper;
15    }
16 }
fastjson
使⽤fastjson需要导⼊依赖(mvnrepository/search?q=fastjson)
1 <dependency>
2    <groupId>com.alibaba</groupId>
3    <artifactId>fastjson</artifactId>
4    <version>1.2.58</version>fastjson怎么用
5 </dependency>
使⽤fastjson时,对null的处理和Jackson有些不同,需要继承WebMvcConfigurationSupport类,然后覆盖configureMessageConverters⽅法。在⽅法中,我们可以选择要实现null转换的场景,配置好即可。
1import com.alibaba.fastjson.serializer.SerializerFeature;
2import com.alibaba.fig.FastJsonConfig;
3import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
4import t.annotation.Configuration;
5import org.springframework.http.MediaType;
6import org.verter.HttpMessageConverter;
7import org.springframework.fig.annotation.WebMvcConfigurationSupport;
8
9import java.nio.charset.Charset;
10import java.util.ArrayList;
11import java.util.List;
12
13 @Configuration
14public class fastJsonConfig extends WebMvcConfigurationSupport {
15
16/**
17    * 使⽤阿⾥ fastjson 作为 JSON MessageConverter
18    * @param converters
19*/
20    @Override
21public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
22        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
23        FastJsonConfig config = new FastJsonConfig();
24        config.setSerializerFeatures(
25// 保留 Map 空的字段
26                SerializerFeature.WriteMapNullValue,
27// 将 String 类型的 null 转成""
28                SerializerFeature.WriteNullStringAsEmpty,
29// 将 Number 类型的 null 转成 0
30                SerializerFeature.WriteNullNumberAsZero,
31// 将 List 类型的 null 转成 []
32                SerializerFeature.WriteNullListAsEmpty,
33// 将 Boolean 类型的 null 转成 false
34                SerializerFeature.WriteNullBooleanAsFalse,
35// 避免循环引⽤
36                SerializerFeature.DisableCircularReferenceDetect);
37
38        converter.setFastJsonConfig(config);
39        converter.setDefaultCharset(Charset.forName("UTF-8"));
40        List<MediaType> mediaTypeList = new ArrayList<>();
41// 解决中⽂乱码问题,相当于在 Controller 上的 @RequestMapping 中加了个属性 produces = "application/json"
42        mediaTypeList.add(MediaType.APPLICATION_JSON);
43        converter.setSupportedMediaTypes(mediaTypeList);
44        converters.add(converter);
45    }
46 }
Jackson VS fastjson
选项FASTJSON杰克逊
上⼿难易程度容易中等
⾼级特性⽀持中等丰富
官⽅⽂档,⽰例⽀持中⽂英⽂
处理JSON速度略快快
关于Jackson和fastjson的对⽐,⽹上有很多资料可以查看,⼤家可以根据⾃⼰实际情况选择合适的框架。从扩展上来看,fastjson没有Jackson灵活,从速度或者上⼿难度来看,fastjson可以考虑,它也⽐较⽅便。