如何使用Swift和Codable递归解析JSON

时间:2019-10-07 09:30:02

标签: swift recursion codable

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

我对标题和副标题不感兴趣,因此我将其从班级中排除。我想从项目中获取Displayname和uri。正如我所说的,该结构更嵌套,但总是相同的结构。是否可以使用递归方式读取元素。 我将以这种方式对其进行解码:

...
let result  = Result { try JSONDecoder().decode(LaunchStructure.self, from: data) } 

谢谢,最好的问候 阿诺德

1 个答案:

答案 0 :(得分:0)

这里根本不需要两种类型,只需一种即可:

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