快速解析嵌套的json对象

时间:2018-10-17 12:31:40

标签: ios json swift

我正在尝试解析具有嵌套对象的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”           }}}

我知道如何解析带有可解码结构的子数组,但不确定如何对此类数据进行同样的操作

1 个答案:

答案 0 :(得分:1)

You can use this

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)
}