Ambran Ambran - 1 year ago 674
Android Question

Kotlin: Iterate through a JSONArray

I'm writing an Android app uding Kotlin and Realm.
I have a JSONArray, and I want to iterate through the JSONObjects in this array in order to load them in a Realm database class:

Realm class:

import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required

open class Person(

@PrimaryKey open var id: Long = 0,

open var name: String = ""

) : RealmObject() {


The JSONArray:


I've tried iterating like the following:

for (item : JSONObject in persons) {


... but I get a
for-loop range must have an iterator() method

Answer Source

Unfortunately, JsonArray does not expose an iterator. So you will have to iterate through it using an index range:

for (i in 0..(persons.length() - 1)) {
    val item = persons.getJSONObject(i)

    // Your code here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download