在JSONObject中处理null [英] Handling null in JSONObject

查看:1890
本文介绍了在JSONObject中处理null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用Eventbrite API,当事件徽标为null时崩溃.

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));

我正在尝试为此事件设置异常,但是我对JSONObjects的经验不是很丰富,而且我不知道if语句的外观如何

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

推荐答案

您必须在

information = jsonObject.getJSONObject("logo");

喜欢

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

请参见此链接

上面写着-public JSONObject getJSONObject (String name)

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

或者,您可以像这样使用optJSONObject-

OR, You can use optJSONObject like this -

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

因为optJSONObject不会引发异常,而是在找不到键的情况下返回null

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

这篇关于在JSONObject中处理null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆