我正在尝试定义一个解码类模型来解码这种 json 文件: 这里有一个简短的提取来理解问题,实际上它是更多嵌套的。
{
"Title" : "Root",
"Subtitle" : "RootTree",
"Launch" : [
{
"DisplayName" : "Clients",
"Launch" : [
{
"DisplayName" : "Clients Details",
"Launch" : [
{
"DisplayName" : "Item1",
"URI" : "/rest/..."
},
{
"DisplayName" : "Item2",
"URI" : "/rest/..."
},
{
"DisplayName" : "Item3",
"URI" : "/rest/..."
}
]
}
]
}
]
}
这里是我的结构,由于递归使用,我使用了一个类:
final class Url: Codable {
let name : String
let uri: String?
let launch: [LaunchStructure]?
enum CodingKeys: String, CodingKey {
case name = "DisplayName"
case uri = "URI"
case launch = "Launch"
}
}
final class LaunchStructure: Codable {
let launch: [Url]
enum CodingKeys: String, CodingKey {
case launch = "Launch"
}
}
我对标题和副标题不感兴趣,因此我已将其从类(class)中排除。我想从项目中获取显示名称和 uri。正如我所说,结构更加嵌套,但结构始终相同。是否可以使用递归方式读取元素。 我将以这种方式解码它:
...
let result = Result { try JSONDecoder().decode(LaunchStructure.self, from: data) }
谢谢,最诚挚的问候 阿诺德
最佳答案
这里根本不需要两种类型,只需一种即可:
struct Item: Codable {
let name : String? // not all entries in your example has it, so it's optional
let uri: String?
let launch: [Item]? // same here, all leaf items doesn't have it
enum CodingKeys: String, CodingKey {
case name = "DisplayName"
case uri = "URI"
case launch = "Launch"
}
}
关于swift - 如何使用 codable 和 swift 递归解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58266834/