A solution where the Null attribute is not shown when fastjson generates json
- 2020-06-07 04:29:55
- OfStack
For 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);
// The output :{"a":1,"b":"",d:"wuzhuti.cn"}
It can be seen from the output that the corresponding key of null has been filtered out. This is obviously not what we want, and we need to use the SerializerFeature serialization property of fastjson
This is the method: JSONObject.toJSONString(Object object, SerializerFeature... features)
SerializerFeature serialization property for Fastjson
QuoteFieldNames -- Whether double quotes are used when key is printed, the default is true
WriteMapNullValue -- Fields with output value null, default to false
WriteNullNumberAsZero -- If the value field is null, the output is 0 instead of null
The WriteNullListAsEmpty -- �List field is null and the output is [], not null
WriteNullStringAsEmpty - If the character type field is null, the output is "" instead of null
The WriteNullBooleanAsFalse Boolean field, if null, outputs false instead of 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);
// The output :{"a":1,"b":"","c":null,"d":"wuzhuti.cn"}