0

I am trying to write a Swift Codable model for the below JSON.

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

The problem is that one of the key changes every time I query. Marked the in the above JSON as (The problem is here)

How to parse the above JSON file with JSONDecoder?

This can be easily parsed with libraries like SwiftyJSON.

Let's_Create
  • 2,963
  • 3
  • 14
  • 33

1 Answers1

2

The point is in making let pages: [String:Item] Use

// 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)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87