source

Kotlin: JSONArray를 통해 반복

bestscript 2023. 2. 16. 22:01

Kotlin: JSONArray를 통해 반복

Kotlin과 Realm을 사용하여 Android 앱을 만들고 있습니다.JSONArray가 있으며 Realm 데이터베이스 클래스에 로드하기 위해 이 배열의 JSONObjects를 반복합니다.

영역 클래스:

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() {

}

JSONAray:

{
    "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
}

심지어 어떤 수업에서 노출이 안 된다고 해도iteratormethod를 사용하여 반복할 수 있습니다.for확장 함수를 제공함으로써 스테이트먼트iterator:

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

이제 사용할 때JSONArrayfor이 확장자는 반복기를 얻기 위해 호출됩니다.인덱스 범위를 생성하고 각 인덱스를 이 인덱스에 해당하는 항목에 매핑합니다.

출연진은 할 것 같다JSONObject는 오브젝트뿐만 아니라 기본 어레이 및 기타 어레이를 포함할 수 있기 때문에 필요합니다.그리고 그asSequence콜을 실행할 수 있습니다.map나태한 조작

일반적인 방법(모든 어레이 엔트리가 동일한 유형이라고 가정)

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

어때.

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

?

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

최단 방법은 다음과 같습니다.

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

기본적으로 0에서 jsonarray lenight까지의 범위에서 한번에 1개의 숫자가 필요하며 현재 개체를 검색하기 위한 인덱스로 사용합니다.

언급URL : https://stackoverflow.com/questions/36184641/kotlin-iterate-through-a-jsonarray