我正在使用Kotlin和Realm编写一个Android应用程序。我有一个JSONArray,我想遍历这个数组中的JSONObjects,以便将它们加载到一个领域数据库类中:
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
错误。
发布于 2016-03-24 01:49:31
不幸的是,JsonArray
没有公开迭代器。因此,您必须使用索引范围对其进行迭代:
for (i in 0 until persons.length()) {
val item = persons.getJSONObject(i)
// Your code here
}
发布于 2018-11-29 12:06:19
怎么样
(0..(jsonArray.length()-1)).forEach { i ->
var item = jsonArray.getJSONObject(i)
}
发布于 2019-06-20 21:35:44
for (i in 0 until jsonArray.length()){
//do your stuff
}
https://stackoverflow.com/questions/36184641
复制相似问题