1.丢失效果
public static void main(String[] args) {
User user = new User();
Map<String, Object> reMap = new HashMap<String, Object>();
reMap.put("aaa",null);
reMap.put("bbb",user);
String json = JSONObject.toJSONString(reMap);
System.out.println(json);
}
2.不丢失效果
用法:JSONObject.toJSONString(Object object, SerializerFeature… features)
public static void main(String[] args) {
User user = new User();
Map<String, Object> reMap = new HashMap<String, Object>();
reMap.put("aaa",null);
reMap.put("bbb",user);
String json = JSONObject.toJSONString(reMap,SerializerFeature.WriteMapNullValue);
String json1 = JSONObject.toJSONString(reMap,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty);
System.out.println("json:"+json);
System.out.println("json1:"+json1);
//import com.alibaba.fastjson.serializer.ValueFilter;
// 自定义空字段处理规则
ValueFilter filter = (obj, s, v) -> {
if (v == null) {
return "";
}
return v;
};
String json2 = JSONObject.toJSONString(reMap,filter);
}
3.SerializerFeature有用的一些枚举值
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null