我在从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属性,对象就可以正常加载(还有大约12个其他属性,所以不仅仅是因为它成功加载了任何东西: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:“期望解码浮点数,但发现了一个数字。”,:nil))
我是不是遗漏了什么?浮点数不是数字吗?我还尝试将isFutureDated的类型更改为Double、Int、Int8、Int16、Int32、Int64、UInt、UInt8……你明白了吧。甚至是数据和字符串。总是同样的错误,将Float部件换出它所期望的任何类型。
最后注意,来自响应对象的实际JSON字段如下:
isFutureDated = 0;
这不是我将在这个特定的应用程序中使用的字段,但如果这个问题再次发生,我希望在它生效之前找到一个解决方案。
发布于 2018-06-05 09:12:25
哦,不要紧。isFutureDated应该是一个布尔值,而不是任何类型的数字。也就是说,
let isFutureDated: Bool?
真奇怪。
https://stackoverflow.com/questions/50690666
复制相似问题