在使用Fastjson解析json时发现,默认处理null时,无论是Map还是Object,结果会把null的字段以及值过滤掉,业务上需要保留null值
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("a", 1);
jsonMap.put("b", "");
jsonMap.put("c", null);
jsonMap.put("d", "appblog.cn");
String str = JSONObject.toJSONString(jsonMap);
System.out.println(str);
//输出结果:{"a":1,"b":"",d:"appblog.cn"}
从输出结果可以看出,null对应的key已经被过滤掉,我们也可以使用Fastjson的SerializerFeature序列化属性
JSONObject.toJSONString(Object object, SerializerFeature... features)
Fastjson的SerializerFeature序列化属性
QuoteFieldNames: 输出key时是否使用双引号,默认为trueWriteMapNullValue: 是否输出值为null的字段,默认为falseWriteNullNumberAsZero: 数值字段如果为null,输出为0,而非nullWriteNullListAsEmpty: List字段如果为null,输出为[],而非nullWriteNullStringAsEmpty: 字符类型字段如果为null,输出为"",而非nullWriteNullBooleanAsFalse: Boolean字段如果为null,输出为false,而非null
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("a", 1);
jsonMap.put("b", "");
jsonMap.put("c", null);
jsonMap.put("d", "appblog.cn");
String str = JSONObject.toJSONString(jsonMap, SerializerFeature.WriteMapNullValue);
System.out.println(str);
//输出结果:{"a":1,"b":"","c":null,d:"appblog.cn"}