net.sf.json.JSONObject保留值为空的KEY
问题:
在使用net.sf.json.JSONObject的过程中,发现net.sf.json.JSONObject 放入空值后,结果在对象里连空值的KEY都找不到。而这里希望即便是空值,KEY也予以保留。
@Test
public void testJson2(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("ID", "ID123456");
jsonObject.put("name", "");
jsonObject.put("extName", "");
jsonObject.put("size", "");
jsonObject.put("type", "");
jsonObject.put("signature", "");
jsonObject.put("createTime", new Date());
jsonObject.put("modifyTime", null);
jsonObject.put("nullobj", JSONNull.getInstance());
jsonObject.put("parentId", "parentId");
System.out.println("result:" + jsonObject);
}
结果:
result:{"ID":"ID123456","name":"","extName":"","size":"","type":"","signature":"","createTime":{"time":1530673135923,"minutes":58,"seconds":55,"hours":10,"month":6,"year":118,"timezoneOffset":-480,"day":3,"date":4},"nullobj":null,"parentId":"parentId"}
可以看到modifyTime值为null,在添加进JSONObject中后,key丢失。
解决:
(1)使用JSONNull
先判断放入对象值是否为空,若为空,则使用JSONNull对象代替null对象
jsonObject.put("nullobj", JSONNull.getInstance());
(2)使用JSONObject.fromObject()进行转换
先将键值对都放入一个MAP对象,然后再将MAP对象转换为JSONObject对象:
@Test
public void testJson(){
Map<String, Object> jsonObject = new HashMap<String,Object>();
jsonObject.put("ID", "ID123456");
jsonObject.put("name", "");
jsonObject.put("extName", "");
jsonObject.put("size", "");
jsonObject.put("type", "");
jsonObject.put("signature", "");
jsonObject.put("createTime", new Date());
jsonObject.put("modifyTime", null);
jsonObject.put("nullobj", JSONNull.getInstance());
jsonObject.put("parentId", "parentId");
JSONObject result = JSONObject.fromObject(jsonObject);
System.out.println("result:" + result);
}
结果:
result:{"extName":"","parentId":"parentId","createTime":{"time":1530673573536,"minutes":6,"seconds":13,"hours":11,"month":6,"year":118,"timezoneOffset":-480,"day":3,"date":4},"nullobj":null,"name":"","ID":"ID123456","type":"","modifyTime":null,"signature":"","size":""}
可以看到值为null的KEY modifyTime没有丢失,正常的显示。