情况
public static void main(String[] args) {
Map<String, Object> resultMap=new HashMap<String, Object>();
resultMap.put("status", 1);
resultMap.put("msg", "success");
resultMap.put("data", null);
System.out.println(JSONObject.toJSONString(resultMap));
}
结果
{"msg":"success","status":1}
从输出结果可以看出,null对应的key已经被过滤掉;这明显不是我们想要的结果,这时我们就需要用到fastjson的SerializerFeature序列化属性
也就是这个方法:JSONObject.toJSONString(Object object, SerializerFeature... features) (摘自狂奔的蜗牛Even 博客)
public static void main(String[] args) {
Map<String, Object> resultMap=new HashMap<String, Object>();
resultMap.put("status", 1);
resultMap.put("msg", "success");
resultMap.put("data", null);
System.out.println(JSONObject.toJSONString(resultMap,SerializerFeature.WriteMapNullValue));
}
结果
{"msg":"success","data":null,"status":1}
Fastjson的SerializerFeature序列化属性
--来自oschina bfleeee博客
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null