Java, Parse JSON Objects that I know are null

2019-04-20 10:39发布

问题:

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

回答1:

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

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



回答2:

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



回答3:

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.