Swift 4 decoding nested JSON with random key [duplicate]

怎甘沉沦 提交于 2019-12-11 06:39:57

问题


Im new to Swift 4 and am trying to decode this JSON from the Wikipedia API. I am struggling to define a Struct because all of the examples/tutorials I have found are only nested 1 - 2 levels deep.

Alongside this how can I decode the data when one of the keys is random?

Thanks

{
  "batchcomplete": "",
  "query": {
      "pages": {
          "RANDOM ID": {
              "pageid": 21721040,
              "ns": 0,
              "title": "Stack Overflow",
              "extract": "Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network...."
         }
      }
   }
}

回答1:


This solution works:

//: Playground - noun: a place where people can play
import Foundation
var str = """
{
    "batchcomplete": "",
    "query": {
        "pages": {
            "RANDOM ID": {
                "pageid": 21721040,
                "ns": 0,
                "title": "Stack Overflow",
                "extract": "Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network...."
            }
        }
    }
}
"""
struct Content: Decodable {
    let batchcomplete: String
    let query: Query
    struct Query: Decodable {
        let pages: Pages
        struct Pages: Decodable {
            var randomId: RandomID?
            struct RandomID: Decodable {
                let pageid: Int64
                let ns: Int64
                let title: String
                let extract: String
            }
            init(from decoder: Decoder) throws {
                let container = try decoder.container(keyedBy: CodingKeys.self)
                for key in container.allKeys {
                    randomId = try? container.decode(RandomID.self, forKey: key)
                }
                print(container.allKeys)
            }
            struct CodingKeys: CodingKey {
                var stringValue: String
                init?(stringValue: String) {
                    self.stringValue = stringValue
                }
                var intValue: Int?
                init?(intValue: Int) {
                    return nil
                }
            }
        }
    }
}
let data = str.data(using: .utf8)!
var content = try? JSONDecoder().decode(Content.self, from: data)
print(content)


来源:https://stackoverflow.com/questions/48411637/swift-4-decoding-nested-json-with-random-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!