从Kotlin的许多对象内部获取数组

时间:2018-11-04 13:46:35

标签: kotlin

我试图建立简单的应用程序来提供航班时刻表。问题是我在json网址中有很多对象,并且这些对象中有数组列表,并且由于无法得到致命错误Caused by: org.json.JSONException: Value

,所以无法从对象中获取数组列表

我的数据json API

{
  "result": {
    "response": {
      "airport": {
        "pluginData": {
          "schedule": {
            "arrivals": {
              "data": [
                {
                  "flight": {
                    "identification": {
                      "id": null,
                      "row": 4832637003,
                      "number": {
                        "default": "ZP4801",
                        "alternative": null
                      },
                      "callsign": null,
                      "codeshare": null
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
}

我的用于获取数组列表数据json的代码

  private fun handleJson (jsonString: String?){

        val jsonArray = JSONArray(jsonString)
        val list =  ArrayList<FlightShdu>()
        var x = 0
        while (x < jsonArray.length()){

            val jsonObject = jsonArray.getJSONObject(x)


            list.add(FlightShdu(

                jsonObject.getInt("id"),
                jsonObject.getString("callsign")

            ))


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

    }

1 个答案:

答案 0 :(得分:1)

我通常建议通过数据类来提供JSON的完整结构,因为这种方法一遍又一遍地运行可能会很昂贵...下面重点介绍一种通过名称通过jsonObjects挖掘JSON的方法,然后进入“标识”的最后一层,并填充一个可与生成的对象序列化的数据类

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration
import kotlinx.serialization.json.JsonDecodingException
import kotlinx.serialization.json.JsonElement

val data =
"""
{
 "result": {
  "response": {
   "airport": {
    "pluginData": {
     "schedule": {
      "arrivals": {
       "data": [{
        "flight": {
         "identification": {
          "id": null,
          "row": 4832637003,
          "number": {
           "default": "ZP4801",
           "alternative": null
          },
         "callsign": null,
         "codeshare": null
         }
        }
       }]
      }
     }
    }
   }
  }
 }
}
"""

@Serializable
data class FlightIdentification(
    val id: Int?,
    val row: String,
    val number: IdentificationNumber,
    val callsign: String?,
    val codeshare: String?
) {
    @Serializable
    data class IdentificationNumber(
        val default: String,
        val alternative: String?
    )
}

val json = Json(JsonConfiguration.Stable)

fun JsonElement?.get(name: String): JsonElement? {
    return if (this == null) null
    else this.jsonObject[name]
}

fun handleJson(jsonString: String) {
    val obj = json.parseJson(jsonString)

    val data = obj.get("result").get("response").get("airport").get("pluginData")
        .get("schedule").get("arrivals").get("data")

    if (data != null) {
        val flight = data.jsonArray[0]
            .get("flight").get("identification")
        try {
            val res = json.parse(FlightIdentification.serializer(), flight.toString())

            println(res)
        } catch (e: JsonDecodingException) {
            println("Decode: ${e.message}")
        }
    }
}

handleJson(data)