【问题标题】:Handling null in JSONObject在 JSONObject 中处理 null
【发布时间】:2016-03-09 23:39:06
【问题描述】:

我的应用使用 Eventbrite API,当事件标志为空时它会崩溃。

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 语句应该是什么样子

我尝试了以下方法,但没有成功

jsonObject.getJSONObject("logo")!=null

【问题讨论】:

    标签: android jsonobject


    【解决方案1】:

    你必须在

    中捕捉JSONException
    information = jsonObject.getJSONObject("logo");
    

    喜欢

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

    看到这个link

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

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

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

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

    因为optJSONObject 不会抛出异常,而是在没有找到密钥时返回null

    【讨论】:

      【解决方案2】:

      它崩溃是因为您试图检索一个不存在的对象。如果对象可能是null,您应该改用jsonObject.optJsonObject("logo")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-11
        • 2014-06-19
        • 2017-02-08
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 2014-06-07
        相关资源
        最近更新 更多