android - Kotlin:遍历 JSONArray

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

领域类:

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:

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

我尝试过如下迭代:

for (item : JSONObject in persons) {

}

...但是我得到一个 for-loop range must have an iterator() method 错误。

最佳答案

不幸的是,JsonArray 没有公开迭代器。所以你必须使用索引范围来遍历它:

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

    // Your code here
}

https://stackoverflow.com/questions/36184641/

相关文章:

java - 将 JSONArray 转换为字符串数组

java - Spring MVC + JSON = 406 Not Acceptable

sql - 如何查询空对象的 json 列?

c# - 将 JSON 字符串解析为对象的最简单的 C# 函数是什么?

javascript - JSON.stringify 深层对象

javascript - ngRepeat 按深度属性过滤

python - 无返回时处理 JSON 解码错误

json - 将逻辑表示为 JSON 中的数据

c# - 如何在 C# 中将 `+` 添加到属性名称?

json - 在 shell 脚本中读取 JSON 数据