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

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

我对标题和副标题不感兴趣,因此我已将其从类(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/

相关文章:

java - Java中递归查找二叉树中的最小值

java - 使用递归链接结构解决子集和问题

swift - 如何使用 [String : Any]? 作为 Struct 中符合 Codable 的属性

ios - 3 组件UIPickerView 制作3位数值

ios - 我已经尝试了所有方法,但无法将 Swift 文件导入到 Objective-C 文件

c# - 使用反射通过对象递归并打印树

ios - Swift Codable - 如何编码自定义数组

json - 如何将 Swift 4 编码的 JSON 写入文件?

Swift UIBarButtonItem 添加手势识别器

string - 使用循环遍历字符串并检查 char 作为字典键