【问题标题】:Convert quoted number from JSON (swift)从 JSON 转换引用的数字(swift)
【发布时间】: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


【解决方案1】:

您可以通过实现 Decodable 协议所需的初始化程序 init(from:) 来做到这一点:

extension MyStruct {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let idString = try values.decode(String.self, forKey: .id)
        id = Int(idString)
    }
}

别忘了解码其他属性的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多