Handling null in JSONObject

亡梦爱人 提交于 2019-12-10 12:23:34

问题


My app uses Eventbrite API and it crashes when event logo is null.

JSONObject jsonRootObject = new JSONObject(event);
JSONArray jsonArray = jsonRootObject.optJSONArray("events");
JSONObject jsonObject = jsonArray.getJSONObject(i);
information = jsonObject.getJSONObject("logo");
text = information.getString("url");
name = "eventsImage" + i;
resId = getResources().getIdentifier(name, "id", getPackageName());
new LoadImagefromUrl().execute(new LoadImagefromUrlModel(text, resId));

I am trying to make exception for this event, but I am not very experienced with JSONObjects and I don't know how if statement should look like

I have tried the following, but it didn't work

jsonObject.getJSONObject("logo")!=null

回答1:


You have to catch JSONException in

information = jsonObject.getJSONObject("logo");

like

try{
    information = jsonObject.getJSONObject("logo");
}catch(JSONException je){
    //json object not found
}

See this link

which says - public JSONObject getJSONObject (String name)

Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.

OR, You can use optJSONObject like this -

if(jsonObject.optJSONObject("logo")!=null)'

Because optJSONObject doesn't throws exceptions instead returns null if no key found




回答2:


It crashes because you are trying to retrieve an object that does not exist. If object might be null you should be using jsonObject.optJsonObject("logo") instead.



来源:https://stackoverflow.com/questions/35904865/handling-null-in-jsonobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!