14

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

3
  • Possible duplicate: stackoverflow.com/questions/2456078/java-json-null-exception Commented Sep 21, 2011 at 20:14
  • the answer wouldn't work for me, I can't just use a hashmap because my objects have more than two values to just store. More like 5 or 6 unique key/value pairs Commented Sep 21, 2011 at 20:19
  • 1
    Ah, so your JSON would need to look more like [{"key1":val1},{"key2":val2},{"key3":val3}], then iterate through the array of objects. Commented Sep 21, 2011 at 20:20

3 Answers 3

19

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

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

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

3 Comments

Also check out the other opt...(key) methods for different data types or the general Object opt(key).
optString("promotion",null) returns "null" (not null!) in my case for {"promotion":null}, which I consider to be strange. Javadoc says that null is returned for missing keys, otherwise conversion is made. Probably it is the reason why I get "null" instead of expected null. Seems that I will have to apply the check isNull(), what I tried to avoid. Bad designed API, you poor javascripters! ))
@Pang Thanks for the ping! json.org stopped hosting javadoc, so here's a link to the source code for org.json.JSONObject: github.com/stleary/JSON-java/blob/master/JSONObject.java
1

I think you'll need to format the JSON differently;

for an array of promotions

{promotions:[{promotion:null}, {promotion:5000}]}

for a single promotion

{promotion:null}

edit: depending on which json api you're using, there might be a null check. Google's gson library has an .isJsonNull() method

Comments

0

Uh...I don't think that is a properly formatted JSON string. [] indicates an array, which doesn't have any kind of key=>value pairing like an object does. What I think you want would be {"promotion":null}, which then your code snippet likely would work.

1 Comment

I'm pretty sure JSON array can't have pairs, just values. See json.org. So ["promotion":null] is invalid JSON.

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.