Home > OS >  Using Kotlin to parse nested json array/object
Using Kotlin to parse nested json array/object

Time:06-03

I've read a few posts on here saying to use gson or something else. Android Kotlin parsing nested JSON

I am planning on switching to gson later but wondering how to parse with kotlin.

JSON object:

{
   "childScoresList":[     // line 1,2 gets the JSON array
   {
         "child_id":"1",
         "score_date":"2022-03-27",
         "category_id":"1",
         "category_name":"Preschool Math",    // line 3,4 gets this data
         "classes":[
         {
               "category_name":"Preschool Math",    
               "class_name":"Number Blocks",       // How do I get class_name which is nested? 
               "class_id":"1",
               "class_description":"Ones, Tens, Hundreds Blocks used to create given numbers.",
               "skills":[
               {
                     "skill_id":"1",
                     "skill_name":"Place Value",   // After I figure out class_name, skill_name should be very similar
                     "skill_description":"Knowing the place value of specific elements.",
                     "skill_score":"50"
               },

Kotlin code:

1   val obj = JSONObject(response.toString())
2   val jsonArray = obj.getJSONArray("childScoresList")
3   for (i in 0 until jsonArray.length()) {
4        val categoryName = jsonArray.getJSONObject(i).getString("category_name")
5    } 

How do I get data in class_name? I tried various things but could not get it to work.

CodePudding user response:

You must first get JSONArray from the object according to the following code and then access the class_name variable

val obj = JSONObject(js)
val jsonArray = obj.getJSONArray("childScoresList")
for (i in 0 until jsonArray.length()) {
    val classes = jsonArray.getJSONObject(i).getJSONArray("classes")
    for (x in 0 until classes.length()) {
        val categoryName = classes.getJSONObject(x).getString("category_name")
        val className = classes.getJSONObject(x).getString("class_name")
    }
}
  • Related