【发布时间】:2021-04-27 19:34:41
【问题描述】:
我有一个像下面这样的结构:
struct MyStruct: Codable {
var id: Int?
}
我从服务器收到的 JSON 是这样的:
{
"id": 12345
}
但现在服务器端决定将所有数字作为带引号的数字发送,如下所示:
{
"id": "12345"
}
使用JSONDecoder().decode 解码此 json 时出现错误,
The data couldn’t be read because it isn’t in the correct format
有什么办法(除了为我到目前为止创建的每个结构编写自定义的 Encodable 和 Decodable 实现)来解决这个问题吗?例如在JSONDecoder()上做某事
【问题讨论】:
-
不行,需要手动转换
-
这不是一个引用的数字,它是
String。声明let id: String。永远不要print(error.localizedDescription),而是print(error)。它会告诉你真正的错误。
标签: ios json swift json-deserialization jsondecoder