gpt4 book ai didi

kotlin - 检查 JSON 是否是 kotlin 中的 JSONObject 或 JSONArray

转载 作者:行者123 更新时间:2023-12-02 17:02:04 27 4
gpt4 key购买 nike

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

{
"result": {
"response": {
"data": [
{
"identification": {
"id": null,
"number": {
"default": "IA224",
"alternative": null
},
"callsign": null,
"codeshare": null
}
}
]
}
}
}

但有时这个数据可以是(JSON对象)或者如果我输入了错误的信息则为空

data :  null

我想在它的对象上做不同的操作,而在它的数组上做不同的操作。我收到以下异常

Caused by: org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray

我做了这段代码,但他没有工作

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

if(jsonArray.isNull(0)){
jsonArray.getJSONObject(0).getString("data");
}

最佳答案

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

            val jsonObj = JSONObject(jsonString)

if(jsonObj is JsonArray){
//handle operation with JsonArray
}else if (jsonObj is JsonObject){
// treat this as JsonObject
}

您还可以在 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}
}

更新 - 对于你的 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")

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

关于kotlin - 检查 JSON 是否是 kotlin 中的 JSONObject 或 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658261/

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