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.

2 comments:

  1. We Make Strategies, Searching for Websites Development To Create Valuable Websites and Products With Unique Business Ideas and The Passionate People Behind.

    ReplyDelete
  2. CodeRunner is helpful for developers primarily for its code compiling abilities. This IDE cum code editor can be useful for an apple app developer to create potent and advanced applications. CodeRunner supports 25 programming languages and is extremely lightweight. It has a built-in console, premier text editor, and customised key binding. If you are an experienced freelance apple app developer, then you can find premium development projects from top clients on Eiliana.com.

    ReplyDelete