如何使用可解码的解析数组?

时间:2018-11-26 18:06:08

标签: ios arrays swift decodable

如何使用可解码协议解析此类数组?

请提供任何建议或示例代码?

{
    "prices": [
        [
            1543165872687,
            3806.312680456958
        ],
        [
            1543166191453,
            3773.774449897494
        ],
        [
            1543166462780,
            3761.2358246729386
        ],
        [
            1543166765273,
            3765.5068929779973
      ]
    ]
}

我的呼叫服务功能如下:

  ServiceConnector.shared.connect(.GetCoinGeckoChartData(id: id, currcy: currency, days: days), success: { (target,data) in
            self.hideProgressHUD()

            do {
                let array = try JSONDecoder().decode([CoinGeckoChartData].self, from: data)
               }
            catch let err {
                print("CoinGeckoChartData json parsing err : ",err)
            }
        })

2 个答案:

答案 0 :(得分:1)

这是尝试解析为似乎更好地匹配json数据的int&double结构

struct Item: Decodable {
    var prices: [PriceInfo]
}

struct PriceInfo: Decodable {
    var id: Int
    var price: Double

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        id = Int(try container.decode(Double.self))
        price = try container.decode(Double.self)
    }
}

答案 1 :(得分:0)

该数组只是一个数组数组。内部数组中存储的值都是Double,因此您可以使用以下结构:

struct Foo : Decodable {
    let prices: [[Double]]
}