问题:
使用JSONObject jsonObject = JSONObject.parseObject(obj);转换成Json对象时,fastjson会保留所有的键值对。但是使用String jsonStr = JSON.toJSONString(o);把对象转化成字符串时,fastjson会自动去除值为null的键。示例如下:
public static void getJsonString() {
String s = "{\"id\":100,\"townName\":null,\"countyName\":null}";
JSONObject jsonObject = JSON.parseObject(s);
System.out.println("jsonObject 包含:"+jsonObject.keySet().toString());
String jsonStr = JSON.toJSONString(jsonObject);
System.out.println("json字符串:"+jsonStr);
}
打印输出结果:
jsonObject 包含:[townName, id, countyName]
json字符串:{"id":100}
解决:
在转成json字符串时,fastjson支持指定序列化模式,可以支持保留null值得键。改为:
String jsonStr = JSON.toJSONString(jsonObject,SerializerFeature.WRITE_MAP_NULL_FEATURES);
public static void getJsonString() {
String s = "{\"id\":100,\"townName\":null,\"countyName\":null}";
JSONObject jsonObject = JSON.parseObject(s);
System.out.println("jsonObject 包含:"+jsonObject.keySet().toString());
String jsonStr = JSON.toJSONString(jsonObject,SerializerFeature.WRITE_MAP_NULL_FEATURES);
System.out.println("json字符串:"+jsonStr);
}
打印结果:
jsonObject 包含:[townName, id, countyName]
json字符串:{townName:null,id:100,countyName:null}
但是出现新的问题,json字符串键的双引号不见了。查看fastjson源码,发现JSON.toJSONString方法支持传入多个序列化特性。
源码如下:
/**
* @since 1.2.11
*/
public static String toJSONString(Object object, int defaultFeatures, SerializerFeature... features) {
SerializeWriter out = new SerializeWriter((Writer) null, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(out);
serializer.write(object);
return out.toString();
} finally {
out.close();
}
}
SerializerFeature.QuoteFieldNames作用是设定key值使用双引号,因此,修改为String jsonStr = JSON.toJSONString(jsonObject,SerializerFeature.WRITE_MAP_NULL_FEATURES,SerializerFeature.QuoteFieldNames);
修改后代码:
public static void getJsonString() {
String s = "{\"id\":100,\"townName\":null,\"countyName\":null}";
JSONObject jsonObject = JSON.parseObject(s);
System.out.println("jsonObject 包含:"+jsonObject.keySet().toString());
String jsonStr = JSON.toJSONString(jsonObject,SerializerFeature.WRITE_MAP_NULL_FEATURES,SerializerFeature.QuoteFieldNames);
System.out.println("json字符串:"+jsonStr);
}
结果如下:
jsonObject 包含:[townName, id, countyName]
json字符串:{"townName":null,"id":100,"countyName":null}
至此,fastjson转json字符串自动过滤null值得问题解决