'How to parse JSON in Kotlin
How can I parse JSON in Kotlin? It gets the entire array from JSON but can not get a particular object from the Array.
It worked in Java but not in Kotlin.
try {
val jsonObject = JSONObject(result)
val users = jsonObject.getJSONArray("Users")
for (i in 0 until users.length())
{
Toast.makeText(applicationContext,"Json Result is----"+result,Toast.LENGTH_LONG).show()
val obj = users.getJSONObject(i)
val name = obj.get("name").toString()
Toast.makeText(applicationContext, "User name: "+name , Toast.LENGTH_LONG).show();
}
}catch(e: JSONException){}
Solution 1:[1]
Use jsonObject.getString(paramName: String), not jsonObject.get(paramName: String).toString().
Or you can also cast this object to string. See http://www.docjar.com/docs/api/org/json/JSONObject.html
Solution 2:[2]
The best and quick practice is instead of manually checking for each key, generate native Kotlin "data classes" using tools e.g. https://json2kotlin.com
So your API response turns into the following couple of data classes corresponding to the JSON structure:
data class Json4Kotlin_Base (
val users : List<Users>
)
and
data class Users (
val id : String,
val name : String,
val age : Int,
val gender : String,
val email : Email
)
and
data class Email (
val primary : String,
val secondary : String
)
When you get the result, you simple map the JSON response to these data classes. The video here shows how to do it step by step, and includes more sample code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cililing |
| Solution 2 | Syed Absar |
