Kotlin无法在数组之前反对

时间:2018-11-05 09:24:19

标签: kotlin

当我尝试从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

1 个答案:

答案 0 :(得分:2)

我不确定您要使用哪个库反序列化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
)

请注意,在这两种情况下,我都有最高级的Root类,这是从您的示例中解包顶级{}对象的必要条件