我是SwiftUI的新手,正在尝试加载一个json文件,其中的数据包含如下类型的树结构:
struct Node : Identifiable {
id = UUID()
name : String
childNodes : [Node]
}
数据结构的子节点深度是未知的。
试着解码
guard let results = try? decoder.decode(Node.self, from: filedata) else {
fatalError("Decode error")
似乎有效,直到我尝试使用数据。我猜这可能与childNodes数组在某种程度上是空的事实有关。
实现这一目标的最佳方法是什么?
不确定这是否有帮助,但我通过使用老式的JSONSerialization
解决了一个模糊的类似问题。通过强制转换到[String : Any]
,您不需要知道嵌套对象的结构。深入研究它们就不那么干净了,但这是一种权衡:
guard let results = try JSONSerialization
.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
print("didn't work")
return
}
如果键nodes
存在于任何字典中,并且[]
表示空数组,则可以简单地使用此结构体解码JSON
struct Node : Decodable {
let id : Int
let name : String
let nodes : [Node]
}
为方便起见,您可以添加一个computed属性来指示该节点是叶子
struct Node : Decodable {
let id : Int
let name : String
let nodes : [Node]
private enum CodingKeys : String, CodingKey { case id, name, nodes }
var isLeaf : Bool { return nodes.isEmpty }
}