Home > front end >  How to decode this .json to swift model as this json does not have keys?
How to decode this .json to swift model as this json does not have keys?

Time:04-06

{"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.

CodePudding user response:

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
}

CodePudding user response:

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.

CodePudding user response:

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