【问题标题】:How to create a Swift model for the JSON file with dynamic key?如何使用动态键为 JSON 文件创建 Swift 模型?
【发布时间】:2020-06-26 10:53:11
【问题描述】:

我正在尝试为下面的 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中的标记为(问题出在这里)

如何用JSONDecoder解析上述JSON文件?

这可以使用 SwiftyJSON 等库轻松解析。

【问题讨论】:

标签: ios json swift jsondecoder


【解决方案1】:

重点在于让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)

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 2023-01-31
    • 2021-11-22
    • 2020-05-22
    • 2015-06-22
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多