Codable 与 swiftyjson。如何将我的代码转换为 Codable(值数组)

Codable verses swiftyjson. How to convert my code to Codable (array of values)

很多人告诉我,codable 比使用 swiftyjson 好得多,所以我正在尝试一下。我想将此 JSON、https://api.gdax.com/products/BTC-USD/book?level=2 中的 return 转换为两个数组(一个用于询问,一个用于出价)。我还想要单独变量中的序列值。这就是我使用 swiftyjson 的方式。这将如何使用 codable 完成?我为此使用了 alamofire。

这是 Alamofire 调用,但它非常简单且无关紧要。

Alamofire.request(url, method: .get).responseJSON {(response) in
    switch response.result{
    case .success(let value):

这里是重要的代码:

let swiftyJson = JSON(value)

guard let sequenceNum = Int(swiftyJson["sequence"].stringValue) else {return}

let askOrders = swiftyJson["asks"].arrayValue
let bidOrders = swiftyJson["bids"].arrayValue

let askSideBook = askOrders.map({ (obj) -> (price:Double, size:Double, numOrders:Double) in
    let orderArray = obj.arrayValue

    let price = orderArray[0].doubleValue
    let size = orderArray[1].doubleValue
    let numOrders = orderArray[2].doubleValue

    return (price:price, size:size, numOrders:numOrders)
})

let bidSideBook = bidOrders.map({ (obj) -> (price:Double, size:Double, numOrders:Double) in
    let orderArray = obj.arrayValue

    let price = orderArray[0].doubleValue
    let size = orderArray[1].doubleValue
    let numOrders = orderArray[2].doubleValue

    return (price:price, size:size, numOrders:numOrders)
})

这里是 JSON 的缩写,但它会让您了解一般格式。如您所见,第一个值是价格,第二个是尺寸,第三个是订单数量。价格和尺寸都 return 编为字符串,但我需要它们为双精度。

{
  "sequence": 4448910440,
  "bids": [
    [
      "9679.96",
      "9.52707734",
      38
    ],
    [
      "9679.94",
      "0.12631007",
      3
    ],...
  ],
  "asks": [
    [
      "9679.97",
      "45.51632996",
      10
    ],
    [
      "9679.98",
      "1.31689466",
      1
    ],...
  ]
}

我也听说过https://github.com/Otbivnoe/CodableAlamofire。这是推荐的东西吗?

这是我目前所知道的,但我不知道如何通过要价和出价数组中每个项目的索引来处理数组。

struct OrderBookItems: Codable {
    let bidOrderBook: [DataPoints]
    let askOrderBook: [DataPoints]
    private enum CodingKeys: String, CodingKey {
        case bidOrderBook = "bid"
        case askOrderBook = "ask"
    }
}

codingKeys 的值是错误的(复数形式),您需要第二个提供自定义初始化程序的结构来解码数组

struct OrderBookItems: Decodable {
    let bidOrderBook: [DataPoint]
    let askOrderBook: [DataPoint]
    private enum CodingKeys: String, CodingKey {
        case bidOrderBook = "bids"
        case askOrderBook = "asks"
    }
}

struct DataPoint : Decodable {
    let price : Double
    let size : Double
    let numOrders : Int

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        price = Double(try container.decode(String.self)) ?? 0.0
        size = Double(try container.decode(String.self)) ?? 0.0
        numOrders = try container.decode(Int.self)
    }
}