具有不同数组类型的 Swift Codable

标签 swift codable

我正在编写一个程序来解析 JSON包含数组数组的数据,其中嵌套数组具有不同的对象类型(具体来说,[[String, String, Int]])。例如,

{
"number": 5295,
"bets": [
    [
        "16",
        "83",
        9
    ],
    [
        "75",
        "99",
        4
    ],
    [
        "46",
        "27",
        5
    ]
]
}

我正在尝试使用 codable 来帮助我解析数据,但是当我尝试类似的东西时

struct OrderBook: Codable {
    let number: Int
    let bets: [Bet]
}

struct Bet: Codable {
    let price: String
    let sale: String
    let quantity: Int
}

它给我错误的说法

Expected to decode Dictionary<String, Any> but found an array instead

我该如何解决这个问题?我不能声明一个空类型的数组。

最佳答案

一个解决方案(假设您不能更改 JSON)是为 Bet 实现自定义解码逻辑。您可以使用未加密的容器(从 JSON 数组读取)来依次解码每个属性(您调用 decode(_:) 的顺序是它们的预期顺序出现在数组中)。

import Foundation

struct OrderBook : Codable {
  let number: Int
  let bets: [Bet]
}

struct Bet : Codable {
  let price: String
  let sale: String
  let quantity: Int

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

  // if you need encoding (if not, make Bet Decodable
  // and remove this method)
  func encode(to encoder: Encoder) throws {
    var container = encoder.unkeyedContainer()
    try container.encode(price)
    try container.encode(sale)
    try container.encode(quantity)
  }
}

示例解码:

let jsonString = """
{ "number": 5295, "bets": [["16","83",9], ["75","99",4], ["46","27",5]] }
"""

let jsonData = Data(jsonString.utf8)

do {
  let decoded = try JSONDecoder().decode(OrderBook.self, from: jsonData)
  print(decoded)
} catch {
  print(error)
}

// OrderBook(number: 5295, bets: [
//   Bet(price: "16", sale: "83", quantity: 9),
//   Bet(price: "75", sale: "99", quantity: 4),
//   Bet(price: "46", sale: "27", quantity: 5)
// ])

关于具有不同数组类型的 Swift Codable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002429/

相关文章:

ios - 快速启用时在键盘上方显示按钮时出现问题

swift - 如何在 Core Data 中使用 swift 4 Codable?

ios - 选中时如何将 UITableView 单元格分隔符设置为 'None'

Swift:如何创建具有 Int 值的谓词?

ios - 将表格 View 单元格中收藏夹按钮的状态保存在 NSUserDefaults 中

swift - 将模型保存到 Userdefaults 中会使应用程序 swift 崩溃

ios - Swift - 保存 [String : Any] to NSUserDefauls 的数组

ios - 如何在同一容器中解码 DynamicKeys 和 CodingKeys?

Swift 4 Codable - API 有时提供 Int 有时提供 String

ios - 请求有关用户 iOS 的数据