【问题标题】:Error org.json.JSONException: Index 2 out of range错误 org.json.JSONException:索引 2 超出范围
【发布时间】:2018-07-25 16:43:13
【问题描述】:

你好,我的简单 Json 是,我有错误 org.json.JSONException: Index 2 out of range 你能帮我解决这个问题吗? :

[
{
    "cat_id": 593,
    "title": "آلرژی و ایمونولوژی",
    "sub_cat": [
        {
            "cat_id": 594,
            "cat_title": "متخصص",
            "cat_parent_fk": 593
        },
        {
            "cat_id": 595,
            "cat_title": "فوق تخصص",
            "cat_parent_fk": 593
        }
    ]

并使用此代码获取此 json,但我有一些错误,只显示我的 json >15 项中的两项:

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0; i < response.length(); i++) {
                try {
                    Cats cats = new Cats();
                    JSONObject jsonObject = (JSONObject) response.get(i);
                    String cat_id = jsonObject.getString("cat_id");
                    String title = jsonObject.getString("title");
                    String image_add = jsonObject.getString("image_add");
                    String image = jsonObject.getString("image");

                   JSONArray jsonArray = jsonObject.getJSONArray("sub_cat");


                    for (int j = 0; j < jsonArray.length(); j++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        int sub_cat_id = object.getInt("cat_id");
                        String sub_cat_title = object.getString("cat_title");
                        int sub_parent_fk = object.getInt("cat_parent_fk");
                        Log.i("log", "onResponse: "+ sub_cat_id + sub_cat_title + sub_parent_fk);
                    }


                    cats.setCat_id(cat_id);
                    cats.setTitle(title);
                    cats.setImage(image);
                    cats.setImage_add(image_add);
                    list.add(cats);
                    catsAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

【问题讨论】:

    标签: android json android-volley


    【解决方案1】:

    你应该在这里使用j 而不是i

    JSONObject object = jsonArray.getJSONObject(j);
    //                                          ^^
    

    假设您的响应有 3 个 json 对象,每个 sub_cat 有 2 个对象,所以在解析 response 的第三个对象(当 i 为 2 时)但 sublist 有 2 个对象(索引 0, 1)所以知道(如上所述)这将尝试从 2 个对象的数组(sub_cat)中获取第三个对象,因此问题如此使用

    for (int j = 0; j < jsonArray.length(); j++) {
        JSONObject object = jsonArray.getJSONObject(j);
        // j represents the size of sub_cat.        ^^
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 2022-06-14
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多