我正在编写一个程序来解析 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/