【发布时间】:2019-12-10 12:00:05
【问题描述】:
在我的应用程序中,我从需要解析它的 API 获得 JSON 响应。 JSON 如下所示:
{
"itemTemplates":
[
{
"type": "...",
"properties": {
"..": ".."
},
"children": [
{
"type": "..",
"properties": {
"..": ".."
},
"children": [
{
"type": ".."
}
]
},
{
"type": "..",
"properties": {
"value": ".."
}
},
{
"type": "..",
"properties": {
"value": ".."
}
}
]
}
]
}
我为上述响应创建了 Kotlin 数据类,如下所示:
data class ItemTemplate(val itemTemplates: List<Component> = listOf())
data class Component(
val children: List<Children> = listOf(),
val Properties: Properties = Properties(),
val type: String = "")
data class Children(
val properties: Properties = Properties(),
val type: String = "",
val children: List<Children> = listOf())
如您所见,Children 数据类中有一个递归数据类。在 JSON 响应中,每个 Child 本身可以有多个或零个 Children。 在使用数据类时会出现问题。即,我不能遍历 Children,因为它也可能有 Children,我也需要对其进行迭代(等等)。
由于不知道哪个 Child 有 Children 以及我应该迭代多少次才能解析所有内容,所以我开始考虑使用递归函数。但是,不确定这样做是否正确以及如何进行。
有什么建议吗? 谢谢
【问题讨论】:
-
Children 的孩子看起来和 Children 完全一样吗?如果是,这很简单 - 使用 GSON。如果不是 - 很简单,编写一个 ChildrenChild 类,然后使用 GSON。
-
谢谢,@Shark。我的问题主要是关于遍历。如何递归遍历那些嵌套对象。
标签: android kotlin data-class