springboot中返回值json中null轉換空字符串


在實際項目中,我們難免會遇到一些無值。當我們轉JSON時,不希望這些null出現,比如我們期望所有的null在轉JSON時都變成“”“”這種空字符串,那怎么做呢?

Jackson中對null的處理

 1 @Configuration
 2 public class JacksonConfig {
 3     @Bean
 4     @Primary
 5     @ConditionalOnMissingBean(ObjectMapper.class)
 6     public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
 7         ObjectMapper objectMapper = builder.createXmlMapper(false).build();
 8         objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
 9             @Override
10             public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
11                 jsonGenerator.writeString("");
12             }
13         });
14         return objectMapper;
15     }
16 }

 

fastjson

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

1 <dependency>
2     <groupId>com.alibaba</groupId>
3     <artifactId>fastjson</artifactId>
4     <version>1.2.58</version>
5 </dependency>

使用fastjson時,對null的處理和Jackson有些不同,需要繼承WebMvcConfigurationSupport類,然后覆蓋configureMessageConverters方法。在方法中,我們可以選擇要實現null轉換的場景,配置好即可。

 1 import com.alibaba.fastjson.serializer.SerializerFeature;
 2 import com.alibaba.fastjson.support.config.FastJsonConfig;
 3 import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.http.MediaType;
 6 import org.springframework.http.converter.HttpMessageConverter;
 7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 8 
 9 import java.nio.charset.Charset;
10 import java.util.ArrayList;
11 import java.util.List;
12 
13 @Configuration
14 public class fastJsonConfig extends WebMvcConfigurationSupport {
15 
16     /**
17      * 使用阿里 fastjson 作為 JSON MessageConverter
18      * @param converters
19      */
20     @Override
21     public 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可以考慮,它也比較方便

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM