使用 swift 的 Codable 解码 JSON

Decoding JSON with swift's Codable

我正在尝试使用维基百科的 API 从维基百科下载一些 JSON 数据,并尝试通过 swift 的 Codable 对其进行解析。 url 我正在使用 returns 以下内容:

{
  "batchcomplete": "",
  "query": {
    "pageids": [
      "143540"
    ],
    "pages": {
      "143540": {
        "pageid": 143540,
        "ns": 0,
        "title": "Poinsettia",
        "extract": "The poinsettia ( or ) (Euphorbia pulcherrima) is a commercially important plant species of the diverse spurge family (Euphorbiaceae). The species is indigenous to Mexico. It is particularly well known for its red and green foliage and is widely used in Christmas floral displays. It derives its common English name from Joel Roberts Poinsett, the first United States Minister to Mexico, who introduced the plant to the US in 1825."
      }
    }
  }
}

在 swift 我已声明如下:

struct WikipediaData: Codable {
    let batchComplete: String
    let query: Query

    enum CodingKeys : String, CodingKey {
        case batchComplete = "batchcomplete"
        case query
    }
}

struct Query: Codable {
    let pageIds: [String]
    let pages: Page

    enum CodingKeys : String, CodingKey {
        case pageIds = "pageids"
        case pages
    }
}

struct Page: Codable {
    let pageId: Int
    let ns: Int
    let title: String
    let extract: String

    enum CodingKeys : String, CodingKey {
        case pageId = "pageid"
        case ns
        case title
        case extract
    }
}

我不确定上面的数据是否正确建模。具体来说,

let pages: Page

因为返回的页面可能不止一页。

另外,那不应该是字典吗?如果是这样,关键是什么,因为它是数据(在上述情况下为“143540”)而不是标签?

希望你能给我指出正确的方向。

谢谢

既然你的 pageIdsString,你的 pageId 也应该是。此时使用 Dictionary 非常简单,实际上您可以简单地使用

let pages: [String:Page]

你将完成(并以最小的努力获得 Dictionary)。 Codable 似乎是选择 Swift 的理由。我很想知道它最终会带来哪些其他有趣而优雅的解决方案。它已经改变了我对 JSON 永久解析的看法。此外:您的 pages 真的希望 成为 Dictionary.