Ios 如何使用动态密钥为JSON文件创建Swift模型?
我正试图为下面的JSON编写一个Swift可编码模型Ios 如何使用动态密钥为JSON文件创建Swift模型?,ios,json,swift,jsondecoder,Ios,Json,Swift,Jsondecoder,我正试图为下面的JSON编写一个Swift可编码模型 { "batchcomplete": "", "query": { "pages": { "26667" (The problem is here): { "pageid": 26667, "ns": 0, "title": "Spain", "contentm
{
"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这样的库轻松解析。关键在于让页面:[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)