kotlin无法转换为JSONArray

时间:2018-11-05 06:18:49

标签: kotlin

当我尝试获取JSONArray arrivals时出现此错误

这是我的json:

{
  "arrivals": [
    {
      "airline": "Iraqi Airways",
      "alia": "Iraqi Airways IAW",
      "flight": "IA136"
    }
  ]
}

我的代码:

private fun handleJson (jsonString: String?){

        val jsonObj = JSONArray("arrivals")
        val list =  ArrayList<FlightShdu>()
        var x = 0
        while (x < jsonObj.length()){

            val jsonObject = jsonObj.getJSONObject(x)

            list.add(FlightShdu(

                jsonObject.getInt("airline"),
                jsonObject.getString("fn")

            ))


            x++
        }
        val adapter = ListAdapte(this@MainActivity,list)
        flightShdu_list.adapter = adapter

    }

1 个答案:

答案 0 :(得分:0)

我听不懂你的代码,写得一样

尝试

fun test(){
    handleJson("""{
        "arrivals": [
        {
            "airline": "Iraqi Airways",
            "alia": "Iraqi Airways IAW",
            "flight": "IA136"
        }
        ]
    }""")
}

data class FlightShdu(
        val airline:String,
        val alia:String,
        val flight:String? = null
)
private fun handleJson (jsonString: String?){
    val jsonObj = JSONObject(jsonString)
    val jsonArray = JSONArray(jsonObj.get("arrivals").toString())
    val list =  ArrayList<FlightShdu>()
    var x = 0
    while (x < jsonArray.length()){

        val jsonObject = jsonArray.getJSONObject(x)

        list.add(FlightShdu(

                jsonObject.getString("airline"),
                jsonObject.getString("alia")

        ))
        x++
    }

    list.forEach(::println)
}

您的json以{开头,因此请转换为JSONObject

fn来自哪里?

airlineIraqi Airways可以转换为String