使用swift的Codable解码JSON

时间:2018-04-12 02:19:33

标签: json swift codable

我正在尝试使用他们的API从维基百科下载一些JSON数据,并试图通过swift的Codable解析它。我正在使用的网址返回以下内容:

{
  "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”)而不是标签?

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

感谢

1 个答案:

答案 0 :(得分:2)

由于pageIds String pageIdDictionary也应如此。在这一点上使用let pages: [String:Page] 非常简单,事实上你可以简单地使用

Dictionary

并且您将完成(并且尽可能少地给予Codable)。仅凭pages似乎是接受斯威夫特的理由。我很想知道它最终会带来哪些其他有趣和优雅的解决方案。它已经改变了我对永久JSON解析的看法。此外:您的Dictionary 非常希望成为SELECT REGEXP_REPLACE('20170601', r"^([0-9]{4})([0-9]{2})([0-9]{2})", "\\1/\\2/\\3")