Kotlin: Iterate through a JSONArray

Viewed 68225

I'm writing an Android app using 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,

        @Required
        open var name: String = ""

) : RealmObject() {

}

The JSONArray:

{
    "persons":[
        {
           "id":0,
           "name":"Biatrix"
        },
        {
           "id":1,
           "name":"Bill"
        },
        {
           "id":2,
           "name":"Oren"
        },
        {
           "id":3,
           "name":"Budd"
        }
    ]
}

I've tried iterating like the following:

for (item : JSONObject in persons) {

}

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

5 Answers

How about

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

?

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

shortest way is:

(0 until persons.length()).forEach {
    val item = persons.getJSONObject(it)

Basically from a range taking from zero to the jsonarray lenght ,it takes one number at time and use it as a index to retrieve the current object

Related