Java 检查 JSON 节点是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24899554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:27:43  来源:igfitidea点击:

Check if JSON node is null

javaandroidjson

提问by settheline

I'm returning some JSON from an api, and one of the child nodes of the root object is item.

我正在从 api 返回一些 JSON,根对象的子节点之一是item.

I want to check whether this value at this node is null. Here's what I'm trying, which is currently throwing a JSONExceptionwhen the node actually is null:

我想检查这个节点的这个值是否为空。这是我正在尝试的,JSONException当节点实际上为空时,它当前正在抛出一个:

if (response.getJSONObject("item") != null) {

// do some things with the item node

} else {

// do something else

}

Logcat

逻辑猫

07-22 19:26:00.500: W/System.err(1237): org.json.JSONException: Value null at item of type org.json.JSONObject cannot be converted to JSONObject

Note that the this itemnode isn't just a string value, but a child object. Thank you in advance!

请注意, thisitem节点不仅仅是一个字符串值,而是一个子对象。先感谢您!

采纳答案by Nebu

OK, so if the node always exists, you can check for null using the .isNull() method.

好的,所以如果节点始终存在,您可以使用 .isNull() 方法检查 null。

if (!response.isNull("item")) {

// do some things with the item node

} else {

// do something else

}

回答by Anderson K

First you can check if the key exists, using method has("");

首先,您可以使用方法检查密钥是否存在has("")

if(response.has("item")) {

    if (response.getJSONObject("item") != null) {

        // do some things with the item node

    } else {

        // do something else

    }
}

回答by Dawid Czerwinski

I am assuming that your response is from httpClient right? If so, you can just check the length of it.

我假设您的回复来自 httpClient 对吗?如果是这样,您可以检查它的长度。

HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());

String.valueOf(responseBody.length())

If you are getting anything should be greater than 0 I suppose :)

如果你得到的东西应该大于 0 我想:)