-2

How can I parse this kind of array using decodable protocol ?

any advice or sample code please ?

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

My call service func like this :

  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)
            }
        })
tsniso
  • 621
  • 2
  • 7
  • 16

2 Answers2

1

Here is an attempt to parse to an int & double struct which seems to match the json data better

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)
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

That array is just an array of arrays. The values stored in the inner arrays are all Doubles, so you can use this struct:

struct Foo : Decodable {
    let prices: [[Double]]
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313