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.

1
  • 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 Commented Jun 2, 2022 at 16:59

1 Answer 1

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")
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How do we parse multiple objects in the array?
@IgorGanapolsky With this line, you can see the objects inside the array: val object = jsonArray.getJSONObject(i)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.