djeetee
djeetee

Reputation: 1837

Decoding JSON with swift's Codable

I'm trying to download some JSON data from Wikipedia using their APIs and trying to parse it through swift's Codable. The url I'm using returns the following:

{
  "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."
      }
    }
  }
}

in swift I have declared the following:

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
    }
}

I'm not sure if the above correctly models the data. Specifically,

let pages: Page

as there might be more than one page returned.

Also, shouldn't that be a dictionary? if so, what would the key be since it is data ("143540" in the above case) rather than a label?

I hope you could point me in the right direction.

thanks

Upvotes: 0

Views: 169

Answers (1)

Patru
Patru

Reputation: 4551

Since your pageIds are Strings your pageId should be too. Its mesmerizingly simple to use a Dictionary at this point, in fact you can simply use

let pages: [String:Page]

and you will be done (and given a Dictionary with minimal effort). Codable alone almost seems a reason to pick up Swift. I am intrigued to see to what other interesting and elegant solutions it will lead eventually. It has already changed how I think about JSON parsing permanently. Besides: your pages really want to be a Dictionary.

Upvotes: 4

Related Questions