如何为动态键创建模型,json解析,swift5



我正在解析一个json数据并试图创建一个Model,但不知道如何实现标题并从json数据中提取属性(我已经提供了(,因为pageids属性是动态的。请告诉我如何创建Model以使用id(存储在pageids属性中(从页面提取title属性

jsonData的链接https://en.wikipedia.org/w/api.php?exintro=&标题=坎特伯雷%20bells&indexpageid=&format=json&髓核大小=500&explaintext=&重定向=1&action=查询&prop=提取%7页面图像

我试了一下,下面是我的代码,但我认为这不是正确的

var ID = ""
struct Document:Codable {

let batchcomplete:String
let query:Query
}
struct Query:Codable {
let normalized:[Normalized]

let pages:Pages

var pageids:[String]{
didSet{
ID = oldValue[0]
}
}

}
struct Normalized:Codable {
let from:String
let to:String // it is a name of an flower
}
struct Pages:Codable {
let id:[Pages2]
enum CodingKeys:CodingKey {
case id = "(ID)"
}
}
struct Pages2:Codable {
let title:String // this is an official name of flower
let extract:String // this is a body
let thumbnail:Thumbnail
}
struct Thumbnail:Codable {
let source:String //this is an url for photo
}

映射JSON的模型如下所示:

struct Document: Codable {
let batchcomplete: String
let query: Query
}
struct Query: Codable {
let normalized: [Normalized]
var pageids: [String]
let pages: [String: Page]
}
struct Normalized: Codable {
let from: String
let to: String
}
struct Page: Codable {
let title: String
let extract: String
let thumbnail: Thumbnail
}
struct Thumbnail: Codable {
let source: String
}

并且您可以使用pageids数组和pages字典访问每个页面:

let decoder = JSONDecoder()
do {
let decoded = try decoder.decode(Document.self, from: Data(jsonString.utf8))
decoded.query.pageids.forEach { id in
guard let page = decoded.query.pages[id] else { return }
print(page.title)
}
} catch {
print(error)
}

然而,为了更容易访问页面,我更愿意对模型进行一个小的更改。这将需要习惯性地实现Query结构体的解码:

struct Query: Decodable {
let normalized: [Normalized]
let pages: [Page]

enum CodingKeys: String, CodingKey {
case normalized
case pageids
case pages
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
normalized = try container.decode([Normalized].self, forKey: .normalized)

let pageids = try container.decode([String].self, forKey: .pageids)
let pagesDict = try container.decode([String: Page].self, forKey: .pages)
pages = pageids.compactMap { pagesDict[$0] }
}
}

然后,访问每个页面将像一个循环一样简单:

let decoder = JSONDecoder()
do {
let decoded = try decoder.decode(Document.self, from: Data(jsonString.utf8))
decoded.query.pages.forEach { page in
print(page.title)
}
} catch {
print(error)
}

相关内容

  • 没有找到相关文章

最新更新