4

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!

4 Answers 4

10

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 .

Sign up to request clarification or add additional context in comments.

Comments

8

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

}

2 Comments

This is the correct answer. I wish they never included the has() method.
The method has("tag") is important for scenarios in which for one reason som expected "tag" is not returned(request from RestFull), by this method we can avoid exceptions!!!!
1

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

Comments

-2

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

    }
}

3 Comments

I'm afraid that won't work, because the response always returns the "item" node, but it looks like this "item":null sometimes. Hence, it would bypass the first if statement and then throw the exception at the second if statement.
An exception will be thrown without you perform this call response.getJSONObject ("Item"), and the key 'item' does not exist!
Sorry, I don't understand the meaning of your last comment. The key item will always be present in the Json Object. It's just a matter of whether the value is real data or null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.