I am making calls to a server which can return key-value mappings in the following format:
{...
"mykey":null
...}
I am able to create a JSONObject instance from the above (using the JSONObject(String json) constructor) but am not sure how to determine whether this JSONObject instance has a mapping for “mykey” and that the value of the mapping is null? Would the following check do it…
myJSONObject.has("mykey") && !myJSONObject.isNull("mykey")
… or is there a better way? In particular, I am confused as to whether the JSONObject.NULL object means the same thing as null?
In addition: as well as getting mappings of keys whose value can be null, I need to create JSONObject instances that map null to keys. Would…
myJSONObject.put("mykey", JSONObject.NULL);
… do the job, or is there another way I should be doing this?
If you’re using the built-in Android JSON library, then you’re actually using the (quite capable) libraries from org.json.
https://github.com/douglascrockford/JSON-java
If that’s the case, we can just grep the code to see most of the answers here.
This should hopefully help:
Part 2:
Yep – that seems to be about as good a method as any. In particular, you want to check for null using the isNull method, as JSONObject defines it’s own NULL object (see above).
That’s exactly how you want to do it – in particular, using JSONObject.NULL rather than java’s null (see above again).