关于JSONNull的转换异常问题(JSONNull can not cast to be String)

关于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
发布了37 篇原创文章 · 获赞 29 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42755868/article/details/85243729
今日推荐