English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Solution to not displaying Null properties when generating JSON with fastjson

Let's take an example

Map < String , Object > jsonMap = new HashMap< String , Object>(); 
jsonMap.put("a",1); 
jsonMap.put("b",""); 
jsonMap.put("c",null); 
jsonMap.put("d","wuzhuti.cn"); 
String str = JSONObject.toJSONString(jsonMap); 
System.out.println(str); 
//Output result: {"a":1,"b":"",d:"wuzhuti.cn" 

From the output results, it can be seen that the null corresponding key has been filtered out; this is obviously not the result we want, at this time we need to use fastjson's SerializerFeature serialization attribute

That is to say, this method:JSONObject.toJSONString(Object object, SerializerFeature... features)

Fastjson's SerializerFeature serialization attribute

QuoteFieldNames –-Whether to use double quotes when outputting the key, the default is true

WriteMapNullValue – Whether to output the field whose value is null, the default is false

WriteNullNumberAsZero –-If the numeric field is null, output is 0, not null

WriteNullListAsEmpty – If the List field is null, output is [], not null

WriteNullStringAsEmpty – If the character type field is null, output is "", not null

WriteNullBooleanAsFalse – If the Boolean field is null, output is false, not null

Code

Map < String , Object > jsonMap = new HashMap< String , Object>(); 
jsonMap.put("a",1); 
jsonMap.put("b",""); 
jsonMap.put("c",null); 
jsonMap.put("d","wuzhuti.cn"); 
String str = JSONObject.toJSONString(jsonMap, SerializerFeature.WriteMapNullValue); 
System.out.println(str); 
//Output result: {"a":1,"b":"","c":null,"d":"wuzhuti.cn" 

This solution to the problem that the 'null' attribute does not appear when generating JSON with fastjson is all the content that the editor shares with everyone. Hope it can be a reference for everyone, and I also hope everyone will support the Shout Tutorial more.

You May Also Like