settheline
settheline

Reputation: 3383

Check if JSON node is null

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!

Upvotes: 4

Views: 57392

Answers (4)

Snoi Singla
Snoi Singla

Reputation: 431

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 .

Upvotes: 10

Dawid Czerwinski
Dawid Czerwinski

Reputation: 680

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

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 :)

Upvotes: 1

Nebu
Nebu

Reputation: 1362

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

}

Upvotes: 8

Anderson K
Anderson K

Reputation: 5505

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

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

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

        // do some things with the item node

    } else {

        // do something else

    }
}

Upvotes: -2

Related Questions