I'm returning some JSON from an api, and one of the child nodes of the root object is item
.
I want to check whether this value at this node is null. Here's what I'm trying, which is currently throwing a JSONException
when the node actually is null:
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$1 cannot be converted to JSONObject
Note that the this item
node isn't just a string value, but a child object. Thank you in advance!
To do a proper null check of a JsonNode field:
JsonNode jsonNode = response.get("item");
if(jsonNode == null || jsonNode.isNull()) { }
The item is either not present in response, or explicitly set to null .
OK, so if the node always exists, you can check for null using the .isNull() method.
if (!response.isNull("item")) {
// do some things with the item node
} else {
// do something else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With