【问题标题】:Parsing nested json objects in swift [duplicate]快速解析嵌套的json对象[重复]
【发布时间】:2019-03-22 03:16:57
【问题描述】:

我正在尝试解析具有嵌套对象的 json 数据。

以下是样本数据

{“时间序列(30 分钟)”:{ "2018-10-16 16:00:00": { “1.开”:“15.4700”, "2. 高": "15.5300", "3. 低": "15.4500", "4. 关闭": "15.5000", “5.卷”:“1521981” }, "2018-10-16 15:30:00": { “1.开”:“15.4600”, "2. 高": "15.4950", "3. 低": "15.4400", "4. 关闭": "15.4700", “5.卷”:“397948” }}}

我知道如何解析带有可解码结构的子数组,但不知道如何处理此类数据

【问题讨论】:

  • 你的意思是你不能为这个json写结构吗???
  • 我已经为此创建了结构,并且我正在获取类似这样的数据 Optional(EQUINOX.JSONValue.object(["2018-09-26 13:30:00": EQUINOX.JSONValue. object(["3.low": EQUINOX.JSONValue.string("16.5600"), "2.high": EQUINOX.JSONValue.string("16.6000"), "5.volume": EQUINOX.JSONValue.string(" 271397"), "1. open": EQUINOX.JSONValue.string("16.5700")])). 我不明白的是如何从上面的数据中获取字符串。我跟着medium.com/grand-parade/…写了structs .

标签: ios json swift


【解决方案1】:

你可以用这个

struct Root: Codable {

    let timeSeries: [String: InnerItem]

    enum CodingKeys: String, CodingKey {
        case timeSeries = "Time Series (30min)"
    }
}

struct InnerItem: Codable {

    let open,high,low,close,volume: String 

    enum CodingKeys: String, CodingKey {
        case open = "1. open"
        case high = "2. high"
        case low = "3. low"
        case close = "4. close"
        case volume = "5. volume"
    }
}

do {
   let res = try JSONDecoder().decode(Root.self,from:jsonData)
}
catch {
   print(error)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    相关资源
    最近更新 更多