我从 api 返回一些 JSON,根对象的子节点之一是 item
。
我想检查该节点的值是否为空。这是我正在尝试的操作,当节点实际上为 null 时,当前会抛出 JSONException
:
if (response.getJSONObject("item") != null) {
// do some things with the item node
} else {
// do something else
}
日志猫
07-22 19:26:00.500: W/System.err(1237): org.json.JSONException: Value null at item of type org.json.JSONObject$1 cannot be converted to JSONObject
请注意,this item
节点不仅仅是一个字符串值,而且是一个子对象。预先感谢您!
最佳答案
对 JsonNode 字段进行正确的 null 检查:
JsonNode jsonNode = response.get("item");
if(jsonNode == null || jsonNode.isNull()) { }
该项目要么不存在于响应中,要么明确设置为 null 。
关于java - 检查 JSON 节点是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24899554/