如何使用 codable 和 swift 递归解析 json

How parse json recursively using codable with swift

我正在尝试定义一个解码 class 模型来解码这种 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/..."
                        }

                    ]
                }
            ]
        }
        ]
}   

这里是我的结构,由于递归使用,我使用了class:

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"
    }
}