CQM CQM - 28 days ago 7
Java Question

Java, Parse JSON Objects that I know are null

I have an array of JSON objects. To parse these arrays and store the simply data type values, I have to make assumptions of the key names and store them accordingly.

I also know that sometimes the key's values will be null. example

{["promotion":null]}
how would I parse this?

If I try to access a key whose value is null, I get a JSONException. Now this makes sense, but even if I do
if(myJSObject.getString("promotion")!=null)
then I will still get JSON exception when it checks

how would I do a conditional check in my code for null objects so that I can avoid the JSON exception

Answer

Use JSONObject.optString(String key) or optString(String key, String default).

Edit: ... or isNull(String key), of course :)

Comments