原文地址:https://blog.csdn.net/moshowgame/article/details/82823430
問題背景
//設置
Map < String , Object > jsonMap = new HashMap< String , Object>();
jsonMap.put("a",111);
jsonMap.put("b","aaa");
jsonMap.put("c",null);
jsonMap.put("d","blog.csdn.net/moshowgame");
//輸出
String str = JSONObject.toJSONString(jsonMap);
System.out.println(str);
//輸出結果:{"a":111,"b":"aa",d:"blog.csdn.net/moshowgame"}
1
2
3
4
5
6
7
8
9
10
11
12
從輸出結果可以看出,只要value為空,key的值就會被過濾掉,這明顯不是我們想要的結果,會導致一些坑爹的行為。
解決方案
這時我們就需要用到fastjson的SerializerFeature序列化屬性,也就是這個方法:
JSONObject.toJSONString(Object object, SerializerFeature... features)
1
SerializerFeature有用的一些枚舉值
QuoteFieldNames———-輸出key時是否使用雙引號,默認為true
WriteMapNullValue——–是否輸出值為null的字段,默認為false
WriteNullNumberAsZero—-數值字段如果為null,輸出為0,而非null
WriteNullListAsEmpty—–List字段如果為null,輸出為[],而非null
WriteNullStringAsEmpty—字符類型字段如果為null,輸出為”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果為null,輸出為false,而非null
如果是幾句代碼,直接就
String jsonStr =
JSONObject.toJSONString(object,SerializerFeature.WriteMapNullValue);
如果是項目,需要配置FastjsonConverter.java了
package com.softdev.system.likeu.config;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
/**
* 添加fastjson的轉換
*/
@Configuration
public class FastjsonConverter {
@Bean
public HttpMessageConverters customConverters() {
// 定義一個轉換消息的對象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 添加fastjson的配置信息 比如 :是否要格式化返回的json數據
FastJsonConfig fastJsonConfig = new FastJsonConfig();
// 這里就是核心代碼了,WriteMapNullValue把空的值的key也返回
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
// 處理中文亂碼問題
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
// 在轉換器中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setDefaultCharset(Charset.forName("UTF-8"));
stringConverter.setSupportedMediaTypes(fastMediaTypes);
// 將轉換器添加到converters中
return new HttpMessageConverters(stringConverter,fastConverter);
}
}
————————————————
版權聲明:本文為CSDN博主「Moshow鄭鍇」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/moshowgame/java/article/details/82823430