This question already has answers here:
Swift 4 Decodable with keys not known until decoding time
(3个答案)
去年关门了。
我是Swift 4的新手,我正试图从Wikipedia API中解码这个JSON。我正在努力定义一个结构,因为我发现的所有示例/教程都只有1-2层的深度嵌套。
除此之外,当其中一个键是随机的时,如何解码数据?
谢谢
(3个答案)
去年关门了。
我是Swift 4的新手,我正试图从Wikipedia API中解码这个JSON。我正在努力定义一个结构,因为我发现的所有示例/教程都只有1-2层的深度嵌套。
除此之外,当其中一个键是随机的时,如何解码数据?
谢谢
{
"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...."
}
}
}
}
最佳答案
此解决方案有效:
//: 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)