gpt4 book ai didi

kotlin - Kotlin无法在数组之前反对

转载 作者:行者123 更新时间:2023-12-02 12:47:34 24 4
gpt4 key购买 nike

当我尝试从JSONObject ArrivedResult获取json数组时出现此错误。

这是我的json:

{
"ArrivedResult": {
"arrivals": [
{
"ident": "MSR637",
"aircrafttype": "A321",
"actualdeparturetime": 1541399820,
"actualarrivaltime": 1541406652,
"origin": "HECA"
}
]
}
}

我的代码是
private fun handleJson(jsonString: String?) {
val jsonObj = JSONObject(jsonString)
val ArrivedResult = jsonObj.getJSONObject("ArrivedResult")
val jsonArray = JSONArray(ArrivedResult.get("arrivals").toString())

val list = ArrayList<FlightShdu>()
var x = 0
while (x < jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(x)
list.add(FlightShdu(
jsonObject.getString("aircrafttype"),
jsonObject.getString("destination")
))
x++
}
}

我得到的错误是 Caused by: org.json.JSONException: No value for ArrivedResult

最佳答案

我不确定您要使用哪个库反序列化JSON,但是如果您不愿意使用另一个库,那将非常简单。 Klaxon的敌人示例:

// To parse the JSON, install Klaxon and do:
//
// val root = Root.fromJson(jsonString)

import com.beust.klaxon.*

private val klaxon = Klaxon()

data class Root (
@Json(name = "ArrivedResult")
val arrivedResult: ArrivedResult
) {
public fun toJson() = klaxon.toJsonString(this)

companion object {
public fun fromJson(json: String) = klaxon.parse<Root>(json)
}
}

data class ArrivedResult (
val arrivals: List<Arrival>
)

data class Arrival (
val ident: String,
val aircrafttype: String,
val actualdeparturetime: Long,
val actualarrivaltime: Long,
val origin: String
)

或使用 kotlinx.serialization
// To parse the JSON, install kotlin's serialization plugin and do:
//
// val json = Json(JsonConfiguration.Stable)
// val root = json.parse(Root.serializer(), jsonString)

import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.internal.*

@Serializable
data class Root (
@SerialName("ArrivedResult")
val arrivedResult: ArrivedResult
)

@Serializable
data class ArrivedResult (
val arrivals: List<Arrival>
)

@Serializable
data class Arrival (
val ident: String,
val aircrafttype: String,
val actualdeparturetime: Long,
val actualarrivaltime: Long,
val origin: String
)

请注意,在这两种情况下,我都有top-leve Root类,需要从您的示例中解开顶层 {}对象

关于kotlin - Kotlin无法在数组之前反对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53151506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com