检查 JSON 是 kotlin 中的 JSONObject 还是 JSONArray

Ali*_*san 3 kotlin

我正在从我的服务器获取 JSON 字符串。我的数据看起来像这样(JSON 数组)

{
  "result": {
    "response": {
      "data": [
        {
          "identification": {
            "id": null,
            "number": {
              "default": "IA224",
              "alternative": null
            },
            "callsign": null,
            "codeshare": null
          }
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但有时如果我输入了错误的信息,此数据可能是(JSON 对象)或为空

data :  null
Run Code Online (Sandbox Code Playgroud)

我想在其对象时执行不同的操作,在其数组时执行不同的操作。我收到以下异常

Caused by: org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
Run Code Online (Sandbox Code Playgroud)

我做了这个代码,但他不工作

val jsonArray = JSONArray(response.get("data").toString())

            if(jsonArray.isNull(0)){
               jsonArray.getJSONObject(0).getString("data");
            }
Run Code Online (Sandbox Code Playgroud)

sil*_*war 5

您可以使用is运算符检查对象是否是 JsonObject 或 JsonArray,如下所示

            val jsonObj = JSONObject(jsonString)

            if(jsonObj is JsonArray){
                  //handle operation with JsonArray
            }else if (jsonObj is JsonObject){
                  // treat this as JsonObject
            }
Run Code Online (Sandbox Code Playgroud)

您还可以使用kotlin 中的when表达式来检查这些条件,例如

            when(jsonObj){
                is JsonObject -> { // treat this as JsonObject}
                is JsonArray -> { //treat this as JsonArray}
                else -> { //I have to find some other way to handle this}
            }
Run Code Online (Sandbox Code Playgroud)

更新- 对于你的 Json,解析应该像这样完成

为下面的 json 说 Xyz.kt 创建 pojo

 {
  "identification": {
    "id": null,
    "number": {
      "default": "IA224",
      "alternative": null
    },
    "callsign": null,
    "codeshare": null
  }
}

    val resultJson = JSONObject(jsonString)
    val responseJson = resultJson.getJsonObject("response")
    val dataList = responseJson.getJsonArray("data")
Run Code Online (Sandbox Code Playgroud)

如果每次你得到相同的 Json 响应结构,那么你不必检查 dataList 是 JsonArray 还是 JsonObject。您可以简单地迭代 dataList 来获取 Xyz 对象列表,或者使用 get() 方法获取第一个 JsonElement(Xyz 对象)。