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

2019-07-25 16:37发布

Hello My simple Json is and i have error org.json.JSONException: Index 2 out of range can you help me to solve this problem ? :

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

and get this json with this code but i have some error and just show two item of my json >15 item :

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

1条回答
Lonely孤独者°
2楼-- · 2019-07-25 16:56

Instead of i you should use j here as

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

Let's assume that your response has 3 json objects and every sub_cat has 2 objects so during the parsing of 3rd object of response (when i is 2) but sublist has 2 objects (index 0,1) so know (as mentioned above) this will try to fetch 3rd object from an array(sub_cat) of 2 objects, hence the issue so use

for (int j = 0; j < jsonArray.length(); j++) {
    JSONObject object = jsonArray.getJSONObject(j);
    // j represents the size of sub_cat.        ^^
    ...
}
查看更多
登录 后发表回答