Java, Parse JSON Objects that I know are null

2019-04-20 10:34发布

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条回答
欢心
2楼-- · 2019-04-20 10:54

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

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

查看更多
神经病院院长
3楼-- · 2019-04-20 11:02

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

查看更多
姐就是有狂的资本
4楼-- · 2019-04-20 11:08

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.

查看更多
登录 后发表回答