我正在尝试解码以下 JSON 响应:
{"success":true,"initialprice":"0.00003592","price":"0.00006587",
"high":"0.00006599","low":"0.00003499","volume":"0.68979910",
"bid":"0.00006205","ask":"0.00006595"}
Swift 中的结构如下所示:
struct TOTicker : Codable {
public var success : Bool?
public var initialprice : Double?
public var price : Double?
public var high : Double?
public var low : Double?
public var volume :Double?
public var bid :Double?
public var ask :Double?
}
我用来解码的代码行如下:
let decoder = JSONDecoder()
let ticker = try! decoder.decode(TOTicker.self, from: jsonData)
它一直抛出一个 fatal error ,但我不知道为什么。我以前用这个方法解码没有问题。
最佳答案
首先,要知道错误的原因是什么,您应该执行 do-catch
block 而不是 try!
:
do {
let ticker = try decoder.decode(TOTicker.self, from: jsonData)
} catch {
print(error)
}
因此,您会注意到错误是:
typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "initialprice", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))
这似乎很清楚;您的 json 包含 strings 作为值而不是 double 值(浮点值由“”包围)。您应该做的是将 TOTicker
属性声明为:
struct TOTicker : Codable {
public var success : Bool?
public var initialprice : String?
public var price : String?
public var high : String?
public var low : String?
public var volume :String?
public var bid :String?
public var ask :String?
}
现在,您会注意到您能够成功解析它:
let decoder = JSONDecoder()
do {
let ticker = try decoder.decode(TOTicker.self, from: jsonData)
print(ticker)
} catch {
print(error)
}
你应该在日志中看到:
TOTicker(success: Optional(true), initialprice: Optional("0.00003592"), price: Optional("0.00006587"), high: Optional("0.00006599"), low: Optional("0.00003499"), volume: Optional("0.68979910"), bid: Optional("0.00006205"), ask: Optional("0.00006595"))
关于JSON 未解码为结构( fatal error ,Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003573/