This post is related to previous post I made. I wish to map the following nested dictionary:
["A": [["A1": ["A11", "A12"]], ["A2": ["A21", "A22"]]],
"B": [["B1": ["B11", "B12"]], ["B2": ["B21", "B22"]]]
]
into a recursive struct:
Item(title:"",children:
[Item(title:"A",children:
[Item(title:"A1", children:
[Item(title:"A11"),Item(title:"A12")]
)]),
Item(title:"B",children:
[Item(title:"B1"),Item(title:"B2")]
)]
)
with
struct Item: Identifiable {
let id = UUID()
var title: String
var children: [Item] = []
}
To experiment, I started with ["A": [["A1": ["A11"]]], and made a json string:
let json1: String = """
{"title": "", "children":[{"title": "A",
"children": [{"title": "A1",
"children": [{"title": "A11"}]
}]
}]
}
"""
let decoder = JSONDecoder()
let info = try decoder.decode(Item.self, from: json.data(using: .utf8)!)
print(info)
It works only when I include "children": [] in the last node like this:
let json2: String = """
{"title": "", "children":[{"title": "A",
"children": [{"title": "A1",
"children": [{"title": "A11", "children": []}]
}]
}]
}
"""
What do I need to do to make json1 string work, so that even without the input of children, it will take the default value of []?