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); //输出结果:{"a":1,"b":"",d:"wuzhuti.cn"}
As can be seen from the output results, the corresponding null key has been filtered out; it is not clear what we want, then we need to use fastjson sequence of attributes SerializerFeature
This method is:JSONObject.toJSONString(Object object, SerializerFeature... features)
SerializerFeature useful enumerations
QuoteFieldNames ---- output whether the key when double quotes, defaults to true WriteMapNullValue --- whether the output of the field is null, defaults to false WriteNullNumberAsZero- - numeric field if null, the output is 0, not null WriteNullListAsEmpty-- If List field is null, the output is [], not null WriteNullStringAsEmpty- If the character type field is null, the output is "" not null WriteNullBooleanAsFalse-If false Boolean field is null, the output, not null
Now add
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); //输出结果:{"a":1,"b":"","c":null,"d":"wuzhuti.cn"}
However, if the WriteNullStringAsEmpty also added, for the hair does not work? ! ? ! ?
String str = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty); System.out.println(str); //输出结果:{"a":1,"b":"","c":null,"d":"wuzhuti.cn"}
The current solution is to add a filter
private ValueFilter filter = new ValueFilter() { @Override public Object process(Object obj, String s, Object v) { if(v==null) return ""; return v; } }; JSON.toJSONString(jsonMap, filter)
However, heart unhappy, why does not work ah? SerializerFeature.WriteNullStringAsEmpty
fastjson github: https://github.com/alibaba/fastjson