Unfortunately, JsonArray does not expose an iterator. So you will have to iterate through it using an index range:
for (i in 0 until persons.length()) {
val item = persons.getJSONObject(i)
// Your code here
}
Answer from 0x60 on Stack OverflowUnfortunately, JsonArray does not expose an iterator. So you will have to iterate through it using an index range:
for (i in 0 until persons.length()) {
val item = persons.getJSONObject(i)
// Your code here
}
Even if some class doesn't expose an iterator method, you can still iterate it with for statement by providing an extension function iterator:
operator fun JSONArray.iterator(): Iterator<JSONObject>
= (0 until length()).asSequence().map { get(it) as JSONObject }.iterator()
Now when you use JSONArray in for statement this extension is invoked to get an iterator. It creates a range of indices and maps each index to an item corresponding to this index.
I suppose the cast to JSONObject is required as the array can contain not only objects but also primitives and other arrays. And the asSequence call is here to execute map operation in a lazy way.
Generic way (assuming all array entries are of same type)
@Suppress("UNCHECKED_CAST")
operator fun <T> JSONArray.iterator(): Iterator<T>
= (0 until length()).asSequence().map { get(it) as T }.iterator()
Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
Source
Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:
for(Object o: arr){
if ( o instanceof JSONObject ) {
parse((JSONObject)o);
}
}
This is how things were done back in Java 1.4 and earlier.