如何使用动态密钥为 JSON 文件创建 Swift 模型?

How to create a Swift model for the JSON file with dynamic key?

我正在尝试为以下 JSON 编写一个 Swift Codable 模型。

{
    "batchcomplete": "",
    "query": {
        "pages": {
            "26667" (The problem is here): {
                "pageid": 26667,
                "ns": 0,
                "title": "Spain",
                "contentmodel": "wikitext",
                "pagelanguage": "en",
                "pagelanguagehtmlcode": "en",
                "pagelanguagedir": "ltr",
                "touched": "2020-03-14T18:03:48Z",
                "lastrevid": 945549863,
                "length": 254911,
                "fullurl": "https://en.wikipedia.org/wiki/Spain",
                "editurl": "https://en.wikipedia.org/w/index.php?title=Spain&action=edit",
                "canonicalurl": "https://en.wikipedia.org/wiki/Spain"
            }
        }
    }
}

问题是每次查询时,其中一个键值都变了。 将上面的JSON标记为(问题出在这里)

如何用JSON解码器解析上述JSON文件?

这可以用 SwiftyJSON.

这样的库轻松解析

重点在于let pages: [String:Item]使用

// MARK: - Root
struct Root: Codable {
    let batchcomplete: String
    let query: Query
}

// MARK: - Query
struct Query: Codable {
    let pages: [String:Item]
}


// MARK: - Item
struct Item: Codable {
    let pageid, ns: Int
    let title, contentmodel, pagelanguage, pagelanguagehtmlcode: String
    let pagelanguagedir: String
    let touched: Date
    let lastrevid, length: Int
    let fullurl: String
    let editurl: String
    let canonicalurl: String
}

let res = try JSONDecoder().decode(Root.self, from: data)