3

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");
            }

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you for answered , your code is working fine , but there is problem with jsonarray . when l run app l got the response of all json data . !
check updated answer. I hope this will solve your issue
actully its same l got structure for Json response . if l delete expression when or if and try to enter value in edit text and execute l got exception because l entered wrong information and the exception is Caused by: org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray l dont know what l have to do
you can also use Gson or Jackson converter which will directly return object with parsed response
3

Use the below code to identify whether the JSON string is a JSONObject or JSONArray,

var json = JSONTokener(yourJSONString).nextValue()
when (json) {
    is JSONObject -> { //it is a JsonObject
    }
    is JSONArray -> { //it is a JsonArray
    }
    else -> { //handle the odd scenario
    }
}

Comments

0

Create a function like this. Pass a string in a parameter and return a value.

fun isJSONValid(test: String?): Boolean {
    try {
        JSONObject(test)
    } catch (ex: JSONException) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            JSONArray(test)
        } catch (ex1: JSONException) {
            return false
        }
    }
    return true
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.