'How to decode this .json to swift model as this json does not have keys?

{
  "prices": [
    [
      1649057685537,
      46171.36635962779
    ],
    [
      1649057980881,
      46145.23327887388
    ],
    [
      1649058304446,
      46182.34647884338
    ]
  ]
}

What type of decodable model will be needed for this json type to store data.



Solution 1:[1]

I would create a custom type that holds the price and the date of the price where the sub arrays are converted to the correct values in custom init(from:)

struct Root: Codable {
    let prices: [PriceInfo]
}

struct PriceInfo: Codable {
    let price: Double
    let time: Date

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        let value = try container.decode(Int.self)
        time = Date(timeIntervalSince1970: TimeInterval(value) / 1000)
        price = try container.decode(Double.self)
    }
}

Solution 2:[2]

struct Prices: Codable {
  let prices: [[Double]]
}

But you can customize it as you wish, if we had more context we could help farther. For example in the list we know that there will always be two elements one represents high price and the other low price then we can do

struct Price {
  let high: Double
  let low: Double
  init(list: [Double] {
    self.high = list[0]
    self.low = list[1]
  }
}
struct Prices: Codable {
  let prices: [Price]
  enum CodingKeys: String, CodingKey {
    case prices
  }
  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.prices = try container.decode([[Double]].self, forKey: .prices).map(Price.init)
  }
   … todo ecode if you really want to conform to Codable. But just parsing can be just Decodable
}

Solution 3:[3]

I got how to design the model it is going to be something like;

struct ChartPoints: Codable {
    let prices: [[Double]]
}

Designing the model like this is not giving the error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joakim Danielson
Solution 2
Solution 3 v.kumar