1

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": [
    {
      "child_id": "1",
      "score_date": "2022-03-27",
      "category_id": "1",
      "category_name": "Preschool Math",
      "classes": [
        {
          "category_name": "Preschool Math",
          "class_name": "Number Blocks",
          "class_id": "1",
          "class_description": "Ones, Tens, Hundreds Blocks used to create given numbers.",
          "skills": [
            {
              "skill_id": "1",
              "skill_name": "Place Value",
              "skill_description": "Knowing the place value of specific elements.",
              "skill_score": "50"
            }
          ]
        }
      ]
    }
  ]
}

Kotlin code:

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

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

Majid Ahmadi Jebeli
  • 517
  • 1
  • 6
  • 22
Lewis
  • 135
  • 1
  • 10
  • 1
    I'd prefer Jackson - it's the JSON library recommended by Spring. I'd guess that you have to walk the tree to get to class name: childScoresList[i].classes[j].class_name – duffymo Jun 02 '22 at 16:59

1 Answers1

1

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")
    }
}
Majid Ahmadi Jebeli
  • 517
  • 1
  • 6
  • 22