0

Hello guys I have a tricky problem which I've been solving for hours.

This is my JSON response:

  {
"DATA": [
    {
        "Name": "Aha",
        "ListData": [
            {
                "ID": 1
            },
            {
                "ID": 2
            },
            {
                "ID": 3
            }
        ]
    }
]
}

This is what I've done so far:

 try {
        JSONObject jsonObj = new JSONObject(result);
        JSONArray jsonArray = jsonObj.getJSONArray("DATA");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject data = jsonArray.getJSONObject(i);
            JSONArray arr = data.getJSONArray(Constants.LIST_DATA);
            for(int j = 0; j < arr.length(); j++) {
                JSONObject innerData = arr.getJSONObject(i);

                int id = innerData.getInt(Constants.ID);

                item = new HashMap<>();
                item.put(Constants.ID, id);
                itemList.add(item);
            }
        }

    } catch(JSONException e) {
        Log.e("JSONException", "" + e.toString());
    }

But I'm only getting the correct size (3) of the array but I'm getting the same ID which 1. What seems to be wrong with my code? Any help would greatly appreciated. Thanks!

Result is something like this:

ID=1,ID=1,ID=1

Whereas my expected is:

ID=1,ID=2,ID=3
2
  • your id is int , so read by this code int id = innerData.getInt(Constants.ID); and arr.getJSONObject(j); Commented Oct 14, 2015 at 6:46
  • JSONObject innerData = arr.getJSONObject(i); this is wrong replace with JSONObject innerData = arr.getJSONObject(j); Commented Oct 14, 2015 at 6:48

1 Answer 1

5

You should have used

 JSONObject innerData = arr.getJSONObject(j);

you're doing second loop with j=0 and you're trying to getting JSONString from first loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.