166

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

Is it possible to iterate through JSONArray object using Iterator?

2
  • Check this out stackoverflow.com/questions/3408985/… Commented Jan 24, 2011 at 17:21
  • The link on the question returns error 404. Commented Sep 29, 2018 at 18:08

2 Answers 2

286

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Wouldn't it will calling arr.length() on each iteration? So maybe better to put that into vairable and use that in the loop.
Well yes but it will be the same value everytime, but yes its unecessary a variable should be better.
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-).
There is no .length() method on a JsonArray, but there is a .size() method inherited from java.util.List. docs.oracle.com/javaee/7/api/javax/json/JsonArray.html
|
5

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.