Swift 4使用随机密钥解码嵌套的JSON [英] Swift 4 decoding nested JSON with random key

查看:101
本文介绍了Swift 4使用随机密钥解码嵌套的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift 4的新手,正在尝试从Wikipedia API解码此JSON.我正在努力定义一个Struct,因为我发现的所有示例/教程都仅嵌套1-2级.

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?

谢谢

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

这篇关于Swift 4使用随机密钥解码嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆