In my application, I am getting a JSON response from an API which I need to parse it. The JSON looks like this:
{
"itemTemplates":
[
{
"type": "...",
"properties": {
"..": ".."
},
"children": [
{
"type": "..",
"properties": {
"..": ".."
},
"children": [
{
"type": ".."
}
]
},
{
"type": "..",
"properties": {
"value": ".."
}
},
{
"type": "..",
"properties": {
"value": ".."
}
}
]
}
]
}
I have created Kotlin data classes for the above response which looks like this:
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())
As you can see there is a recursive data class in the Children data class. In the JSON response, each Child can have many or zero Children itself. The problem occurs when it comes to using the data classes. i.e. I cannot loop over Children because it may also have Children which I need to iterate over that as well (and so on).
Since it is not known which Child has Children and how many times I should iterate in order to parse everything, I started thinking of maybe using a recursive function. However, not sure if it is correct to do so and how to do it.
Any suggestions? Thanks