【发布时间】:2020-09-30 15:24:00
【问题描述】:
这篇文章与previous post I made相关。我希望映射以下嵌套字典:
["A": [["A1": ["A11", "A12"]], ["A2": ["A21", "A22"]]],
"B": [["B1": ["B11", "B12"]], ["B2": ["B21", "B22"]]]
]
进入递归结构:
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")]
)]
)
与
struct Item: Identifiable {
let id = UUID()
var title: String
var children: [Item] = []
}
为了实验,我从 ["A": [["A1": ["A11"]]] 开始,做了一个 json 字符串:
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)
只有当我在最后一个节点中包含 "children": [] 时它才有效,如下所示:
let json2: String = """
{"title": "", "children":[{"title": "A",
"children": [{"title": "A1",
"children": [{"title": "A11", "children": []}]
}]
}]
}
"""
我需要做什么才能使json1字符串工作,这样即使没有children的输入,它也会采用[]的默认值?
【问题讨论】: