3

I'm using JSON in my android application in the following manner:

  • Send request to a URL & receive JSON response.
  • Parse JSON response & fetch the required element "results" which is a JSON array.
  • Loop on every i'th element of this JSON array and continue with the required operation

Code:

Integer numberOfItemsInResp = pagination.getInt("items");
    JSONArray results = jsonResponse.getJSONArray("results");
    for (int i = 0; i < numberOfItemsInResp; i++){
        JSONObject perResult = results.getJSONObject(i);
    }

Problem is when the i reaches 50, then JSONObject perResult = results.getJSONObject(i) throws "org.json.JSONException: Index 50 out of range [0..50)" Exception.

Is there any limitation attached to JSONArray?

reiley
  • 3,759
  • 12
  • 58
  • 114

2 Answers2

8

What is numberOfItemsInResp? Suggest you do this:

JSONArray results = jsonResponse.getJSONArray("results");
final int numberOfItemsInResp = results.length();
for (int i = 0; i < numberOfItemsInResp; i++){
    JSONObject perResult = results.getJSONObject(i);
}
weston
  • 54,145
  • 21
  • 145
  • 203
  • numberOfItemsInResp is : `Integer numberOfItemsInResp = pagination.getInt("items");` which I'm using to check just how many items will be there in the response – reiley Dec 11 '12 at 21:33
  • 1
    @Sameera the `results` array had fewer elements than the value in their `items` int. By using `.length()` we ensure it's correct. – weston Jan 23 '15 at 12:07
0

Just do a simple debug, see how your array looks like, most likely you don't have enough items in the array as the index you provide, the answers above are pretty clear in this regard.

Marius M
  • 496
  • 9
  • 16