【问题标题】:Codable and custom field decoding [duplicate]可编码和自定义字段解码[重复]
【发布时间】:2019-06-04 08:20:03
【问题描述】:

我正在使用 Codable 协议和 JSONDecoder 来解码从我的网络服务获得的 JSON。它真的很好用。不过,有一件事是我有时会得到不同格式的日期,所以我想为这个字段设置自定义解码。

通过 SO 和 net 浏览,我发现可以做到这一点,但我还必须手动解码所有其他字段。由于我有很多字段,我想自动解码所有字段,然后手动解码这一字段。

这可能吗?

编辑:

我将提供更多信息,因为这个问题似乎造成了很多混乱。

我有很多字段的 JSON。我的结构 Person 采用 Codable。我像这样使用 JSONDecoder

let person = try self.jsonDecoder.decode(Person.self, from: data)

现在所有字段都自动设置为结构。但有时我有一个或多个字段我想手动解码它们。在这种情况下,它只是日期,可以是各种格式。如果可能的话,我想使用同一行:

let person = try self.jsonDecoder.decode(Person.self, from: data)

所有其他字段将被自动解码,而只有 Date 将进行手动编码。

【问题讨论】:

标签: json swift codable


【解决方案1】:

您可以简单地将用于解码的JSONDecoder 中的dateDecodingStrategy 设置为formatted,并提供具有指定格式的DateFormatter,如果失败,则提供其他日期格式。查看带有示例的完整工作代码:

struct VaryingDate: Decodable {
    let a:String
    let date:Date
}

let jsonWithFirstDate = "{\"a\":\"first\",\"date\":\"2019/01/09\"}".data(using: .utf8)!
let jsonWithSecondDate = "{\"a\":\"first\",\"date\":\"2019-01-09T12:12:12\"}".data(using: .utf8)!

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .formatted(dateFormatter)
do {
    try jsonDecoder.decode(VaryingDate.self, from: jsonWithFirstDate) // succeeds
    try jsonDecoder.decode(VaryingDate.self, from: jsonWithSecondDate) // fails, as expected
} catch {
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    try jsonDecoder.decode(VaryingDate.self, from: jsonWithSecondDate) // succeeds with the updated date format
}

【讨论】:

  • 我不认为 OP 是什么意思
  • @7bebMrto 这就是我从问题中理解的,所以让 OP 回答他是否真的是这个意思:)
  • 他清楚地说他有太多的字段要解码,如果他覆盖了解码器,他将不得不手动解码所有这些,他问他是否可以手动解码 1 个字段,然后让其余的无需手动操作即可自动完成。
  • @7bebMr 重点是您不需要手动解码任何字段。 dateDecodingStrategy 会自动为您处理...
  • @LeoDabus 感谢您发现这一点,更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 2023-04-04
  • 2011-06-21
  • 1970-01-01
  • 2014-08-02
相关资源
最近更新 更多