163

Possible Duplicates:
JSON Array iteration in Android/Java
JSONArray with Java

Is it possible to iterate through JSONArray object using Iterator?

Community
  • 1
  • 1
Eugene
  • 59,186
  • 91
  • 226
  • 333

2 Answers2

284

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}
RealHowTo
  • 34,977
  • 11
  • 70
  • 85
Ben McCann
  • 18,548
  • 25
  • 83
  • 101
  • 7
    Wouldn't it will calling arr.length() on each iteration? So maybe better to put that into vairable and use that in the loop. – husayt Mar 07 '12 at 12:05
  • Well yes but it will be the same value everytime, but yes its unecessary a variable should be better. – Henrique C. Aug 06 '13 at 10:34
  • 11
    Depends on the Compiler, Also I believe it'll just be a getter fetching a value which is not mutable from outside the instance, setting a variable would just allocate more memory 8-). – Mathijs Segers Jan 23 '15 at 13:14
  • 1
    There is no `.length()` method on a `JsonArray`, but there is a `.size()` method inherited from `java.util.List`. https://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html – Peter Dec 11 '16 at 02:25
  • Is he referring to https://github.com/stleary/JSON-java/blob/master/JSONArray.java? – Mike Stoddart Jan 13 '17 at 16:08
  • Good Job......!! – Shridutt Kothari Jun 14 '19 at 10:29
5

You can use the opt(int) method and use a classical for loop.

Jean Hominal
  • 16,518
  • 5
  • 56
  • 90