错误 org.json.JSONException:索引 2 超出范围

Error org.json.JSONException: Index 2 out of range

你好我的简单 Json 是,我有错误 org.json.JSONException:索引 2 超出范围你能帮我解决这个问题吗? :

[
{
    "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();
                }
            }

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

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

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

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