关于android:Kotlin:遍历JSONArray

Kotlin: Iterate through a JSONArray

我正在使用Kotlin和Realm编写一个Android应用程序。
我有一个JSONArray,并且我想遍历此数组中的JSONObject以便将它们加载到Realm数据库类中:

领域类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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() {

}

JSONArray:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
   "persons":[
        {
          "id":0,
          "name":"Biatrix"
        },
        {
          "id":1,
          "name":"Bill"
        },
        {
          "id":2,
          "name":"Oren"
        },
        {
          "id":3,
          "name":"Budd"
        }
    ]
}

我已经尝试过如下迭代:

1
2
3
for (item : JSONObject in persons) {

}

...但是出现for-loop range must have an iterator() method错误。


不幸的是,JsonArray没有公开迭代器。 因此,您将不得不使用索引范围遍历它:

1
2
3
4
5
for (i in 0 until persons.length()) {
    val item = persons.getJSONObject(i)

    // Your code here
}


即使某些类未公开iterator方法,您仍然可以通过提供扩展功能iterator来使用for语句对其进行迭代:

1
2
operator fun JSONArray.iterator(): Iterator<JSONObject>
    = (0 until length()).asSequence().map { get(it) as JSONObject }.iterator()

现在,当您在for语句中使用JsonArray时,将调用此扩展名以获取迭代器。 它创建一系列索引,并将每个索引映射到与此索引对应的项目。

我想强制转换为JSONObject是必需的,因为该数组不仅可以包含对象,而且还可以包含基元和其他数组。 而asSequence调用在这里以惰性方式执行map操作。

通用方式(假设所有数组条目均为同一类型)

1
2
3
@Suppress("UNCHECKED_CAST")
operator fun < T > JSONArray.iterator(): Iterator< T >
    = (0 until length()).asSequence().map { get(it) as T }.iterator()


怎么样

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


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