不存在键时处理 Volley

Handling Volley when no key exists

我已经实现了 Volley 和 Recycler 视图来解析和显示来自简单 JSON 文件的几个项目的列表。 有时某个对象中不存在键,但可能会出现在其他对象中。该密钥已使用 object.getInt("someKey").

定义

一旦 Volley 开始解析带有缺失键的对象,它就会跳出 for 循环(对象存储在数组中)并捕获 JSONException e,这正是应用程序的原因在丢失钥匙的情况下应该做的。

但是,我想防止这种行为,并为该特定对象的缺失键使用占位符值,以便成功构建数组列表并填充 recyclerview,从而使应用程序开始正常工作。

我可以使用什么逻辑来实现此行为?

谢谢!

private void parseJSON() {

    String url = "https://example.com/index.json";
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    try {
                        for (int i = 0; i < response.length(); i++) {
                            JSONObject object = response.getJSONObject(i);

                            String title = object.getString("subject");
                            String description = object.getString("message");
                            String imageUrl = object.getString("thumb");
                            Integer threadId = object.getInt("threadId");

                            mList.add(new Item( title, description, threadId));

                        }


                        mItemAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

以上代码中,threadId是key,在JSON的很多对象中可能出现也可能不出现。

您可以先检查对象上是否存在您的密钥

 try {
        for (int i = 0; i < response.length(); i++) {
            JSONObject object = response.getJSONObject(i);

            String title = object.getString("subject");
            String description = object.getString("message");
            String imageUrl = object.getString("thumb");
            Integer threadId;
            if(object.toString().contain("threadId"){
                threadId = object.getInt("threadId");
            }else{
                threadId = 0;
            }
            mList.add(new Item( title, description, threadId));
        }
        mItemAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }

object.getInt("someKey") 是从"somekey" 获取值。如果没有出现somekey 则显示JSONException。而不是这个object.optInt("someKey")。如果出现,它将从 "somekey" 中获取值,否则将跳过。这是简单的解决方案。谢谢

如果我很好地理解了您的问题,请在此处了解您需要做什么,如果您不确定此密钥是否存在,请使用以下内容

jsonObject.optBoolean("yourKey");
        jsonObject.optInt("yourKey");
        jsonObject.optString("yourKey");
        jsonObject.optLong("yourKey");
        jsonObject.optDouble("yourKey");
        jsonObject.optJSONArray("yourKey");

这将确保 jsonObject 将忽略该键(如果它不存在)。