json - Swift 4 使用随 secret 钥解码嵌套的 JSON

标签 json swift decode swift4

<分区>

我是 Swift 4 的新手,正在尝试从维基百科 API 解码此 JSON。我很难定义一个结构,因为我发现的所有示例/教程都只嵌套了 1 - 2 层。

除此之外,当其中一个 key 是随机的时,我如何解码数据?

谢谢

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

关于json - Swift 4 使用随 secret 钥解码嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48411637/

相关文章:

ios - JTAppleCalendar 以编程方式,单元格未显示

iOS swift : UIPanGestureRecognizer on 2 differents views

c++ - 如何解码 windows 64 位十六进制值 : little endian time?

javascript - 从 JSON 文件中检索数据

swift - 从 ArraySlice 中解包字典

javascript - 如何使用 JavaScript 解码 JPEG2000 位数组图像

decode - 奇怪的代码 Amiga "++[>++++++<-]>.>+"

java - 使用 Volley 为 JSON 请求自定义对象绑定(bind)

java - 如何在使用 gson 创建的 Json 中添加自定义对象

c# - 返回 ajax 请求错误的最佳方式是什么?