Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if JSON is a JSONObject or JSONArray in kotlin

Tags:

kotlin

I am getting JSON string from my server. I have data which looks like this (JSON Array)

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

but some times this data can be (JSON object) or be null if l entered wrong information

data :  null

I want to do different operations when its object and different when its an array. I am getting following exception

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

l did this code but he dose not work

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

            if(jsonArray.isNull(0)){
               jsonArray.getJSONObject(0).getString("data");
            }
like image 291
Ali Ghassan Avatar asked Dec 07 '25 11:12

Ali Ghassan


1 Answers

You can check using is operator to check if object is JsonObject or JsonArray as below

            val jsonObj = JSONObject(jsonString)

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

You can also use when expression in kotlin for checking these conditions like

            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}
            }

Update - For your Json,parsing should be done like this

Create pojo for following json say Xyz.kt

 {
  "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")

If everytime you are getting same structure for Json response then you dont have to check if dataList is JsonArray or JsonObject. You can simply iterate through dataList to get list of Xyz objects or get first JsonElement(object of Xyz) using get() method.

like image 95
silwar Avatar answered Dec 11 '25 07:12

silwar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!