Kotlin: Iterate through a JSONArray

for (i in 0 until jsonArray.length()){
    //do your stuff
    }

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()

How about

(0..(jsonArray.length()-1)).forEach { i ->
    var item = jsonArray.getJSONObject(i)
}

?


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
}