【发布时间】:2018-06-05 01:04:32
【问题描述】:
我在从 API 的 JSON 响应中解码银行信息时遇到问题。
这是我的数据结构的相关部分。我创建了 TransactionResponse 对象以简化从响应中提取相关数据:
struct Transaction: Decodable {
... // other properties, not relevant to this
let isFutureDated: Float? /\
... // see above ___________/
}
struct TransactionResponse: Decodable {
let response: Response?
struct Response: Decodable {
...
let transactions: [Transaction]?
}
}
以及我从 JSON 数据对象的转换:
do {
let transactions = try JSONDecoder().decode(TransactionResponse.self, from: data)
} catch let localError {
print(localError)
}
如果我注释掉 isFutureDated 属性,则对象加载得很好(大约有十几个其他属性,所以它不只是成功加载任何内容:P)。当我在数据结构中包含 isFutureDated 属性时,我发现以下错误:
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "response", intValue: nil), CodingKeys(stringValue: "transactions", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "isFutureDated", intValue: nil)], debugDescription: "本应解码 Float,但找到了一个数字。",underlyingError: nil))
我错过了什么吗?浮点数不是数字吗?我还尝试将 isFutureDated 的类型更改为 Double、Int、Int8、Int16、Int 32、Int64、UInt、UInt8 ......你明白了。甚至数据和字符串。总是同样的错误,将 Float 部分换成它所期望的任何类型。
最后,来自响应对象的实际 JSON 字段如下所示:
isFutureDated = 0;
这不是我要在这个特定应用程序中使用的字段,但如果这个问题再次发生,我想在它重要之前找到解决方案。
【问题讨论】:
-
stackoverflow.com/questions/49826140/… 的 cmets 可能会有所帮助。看起来你想要
Bool,而不是Float。