使用 Kotlin 解析嵌套 json array/object
Using Kotlin to parse nested json array/object
我在这里读了一些帖子,说要使用 gson 或其他东西。
我打算稍后切换到 gson,但想知道如何使用 kotlin 进行解析。
JSON 对象:
{
"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 代码:
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 }
如何获取 class_name 中的数据?
我尝试了各种方法,但无法正常工作。
必须先根据以下代码从对象中获取JSONArray,然后访问class_name变量
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")
}
}
我在这里读了一些帖子,说要使用 gson 或其他东西。
我打算稍后切换到 gson,但想知道如何使用 kotlin 进行解析。
JSON 对象:
{
"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 代码:
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 }
如何获取 class_name 中的数据? 我尝试了各种方法,但无法正常工作。
必须先根据以下代码从对象中获取JSONArray,然后访问class_name变量
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")
}
}