关于JSONNull的转换异常问题
最近碰到一个小问题,关于json类型数据取出判断其值是否为空时,出现了转换异常。
代码如下:
JSONObject testJson = new JSONObject();
testJson.put("A","null");
testJson.put("B","hello");
Map testMap = (Map) testJson;
System.out.print(testMap.get("A") == null);
//结果出现JSONNull 不能够转换成String
原因是:
testMap 中当 对应key值的value值为 null 时,则返回的时JSONNull对象
当 key值的value值为 非null 时,则返回的时String对象
解决方式:
JSONObject testJson = new JSONObject();
testJson.put("A","null");
testJson.put("B","hello");
Map testMap = (Map) testJson;
System.out.print(testMap.get("A").equals("null"));//true