Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if JSON node is null

Tags:

java

json

android

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!

like image 873
settheline Avatar asked Oct 13 '25 03:10

settheline


2 Answers

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 .

like image 66
Snoi Singla Avatar answered Oct 14 '25 17:10

Snoi Singla


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

}
like image 29
Nebu Avatar answered Oct 14 '25 17:10

Nebu