springboot中返回值json中null转换空字符串

2023-05-13,,

在实际项目中,我们难免会遇到一些无值。当我们转JSON时,不希望这些null出现,比如我们期望所有的null在转JSON时都变成“”“”这种空字符串,那怎么做呢?

Jackson中对null的处理

 @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;
}
}

fastjson

使用fastjson需要导入依赖(https://mvnrepository.com/search?q=fastjson)

 <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>

使用fastjson时,对null的处理和Jackson有些不同,需要继承WebMvcConfigurationSupport类,然后覆盖configureMessageConverters方法。在方法中,我们可以选择要实现null转换的场景,配置好即可。

 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; @Configuration
public class fastJsonConfig extends WebMvcConfigurationSupport { /**
* 使用阿里 fastjson 作为 JSON MessageConverter
* @param converters
*/
@Override
public 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);
}
}

Jackson VS fastjson

选项 FASTJSON 杰克逊
上手难易程度 容易 中等
高级特性支持 中等 丰富
官方文档,示例支持 中文 英文
处理JSON速度 略快

关于Jackson和fastjson的对比,网上有很多资料可以查看,大家可以根据自己实际情况选择合适的框架。从扩展上来看,fastjson没有Jackson灵活,从速度或者上手难度来看,fastjson可以考虑,它也比较方便。

springboot中返回值json中null转换空字符串的相关教程结束。

《springboot中返回值json中null转换空字符串.doc》

下载本文的Word格式文档,以方便收藏与打印。