Tuesday, 13 October 2020

Check and Parse dynamic Json Data - JSONObject/ JSONArray in Kotlin

When we don't know about which kind of json data (JSONObject/ JSONArray) receiving from web service. In such scenario how to handle json parsing in kotlin-


 val jsonObject = JSONObject(response)
 val jObj = jsonObject.optJSONObject("result_key")

    if (jObj.get("json_key") is JSONArray){ 
      val rejProArr: JSONArray = jObj.getJSONArray("json_key")
  } else if (jObj.get("json_key") is JSONObject) { 
       val rejProObject: JSONObject = jObj.optJSONObject("json_key")
  }
Here json_key either JSONArray or JSONObject, So we can parse accordingly to avoid crash.