import org.json.JSONObject;
String someStringJsonData = "{"someKey": " + "null" + "}";
JSONObject someJsonObjectData = new JSONObject(someStringJsonData);
Object someKey = someJsonObjectData.get("someKey");
if (null == someKey) {
System.out.println("someKey is null");
}
I have the above simple snippet of code. I would expect to see "someKey is null" printed, however, my code never goes in the if loop. I tried printing value of someKey and it shows to be null. Not sure what I am missing.
I tried different values of the jsonString from this post but to no avail.
2
Answers
I needed to do the check for
JSONObject.NULL
and notnull
https://developer.android.com/reference/org/json/JSONObject.html#NULL.Printing the class of someKey helped. Thank you everyone for your time!!
Per its docs, the internal form of the value of a
JSONObject
can contain values of these types:Boolean
,JSONArray
,JSONObject
,Number
,String
, or theJSONObject.NULL
object. Therefore, I would not expect itsget()
method to returnnull
for any key. In your particular case, I would expectsomeJsonObjectData.get("someKey")
to returnJSONObject.NULL
, which will compare unequal tonull
.JSONObject.NULL
is a specific object, so it should be safe to perform==
comparisons with it: