Notice: 函数 WP_Scripts::localize 的调用方法不正确$l10n 参数必须是一个数组。若要将任意数据传递给脚本,请改用 wp_add_inline_script() 函数。 请查阅调试 WordPress来获取更多信息。 (这个消息是在 5.7.0 版本添加的。) in /data/www/appblog/wp-includes/functions.php on line 6131

fastjson生成json时Null属性不显示

在使用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时是否使用双引号,默认为true
  • WriteMapNullValue: 是否输出值为null的字段,默认为false
  • WriteNullNumberAsZero: 数值字段如果为null,输出为0,而非null
  • WriteNullListAsEmpty: List字段如果为null,输出为[],而非null
  • WriteNullStringAsEmpty: 字符类型字段如果为null,输出为"",而非null
  • WriteNullBooleanAsFalse: 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"}
上一篇 Java中finalize的作用
下一篇 fastjson可正常反序列化字符串null