【问题标题】:Swift - JSONEncoder - encode date fields separately in a super classSwift - JSONEncoder - 在超类中分别编码日期字段
【发布时间】:2018-07-27 06:55:41
【问题描述】:

我对 swift 非常陌生,我正在尝试找到一种方法来为扩展 Codable 的类使用默认编码并为某些字段添加单独的数据。

例如,我有一个扩展 Codable 的 Contact 类,有很多 字段,我想对日期进行不同于默认的编码(默认情况下 JSONEcoder 将日期作为时间戳,但我想使用不同的格式) 为简单起见,假设我的班级是:

class Contact:Codable {
    var name: String?
    var id: String?
    var birthdate: Date?
} 

对于自定义编码,我使用了这个链接:Using Decodable in Swift 4 with Inheritance

问题是我不想单独编码每个字段,因为默认编码会这样做。我只想将某些值添加到编码的 json 中。

我还发现了这个关于动态键的链接,但我不知道如何准确地使用它:https://gist.github.com/samwize/a82f29a1fb34091cd61fc06934568f82

这个可以吗?

【问题讨论】:

  • “以不同方式编码日期”是什么意思?
  • @Sweeper:默认情况下,JSONEcoder 将日期序列化为时间戳,但我想使用不同的格式
  • @vadian:合成的en-/decoder是什么意思?

标签: json swift jsondecoder jsonencoder


【解决方案1】:

如果您只想对日期进行不同的编码,可以将JSONEncoderdateEncodingStrategy 设置为预设值之一。

如果您的编码方式非常特殊,您可能希望将其设置为.customformatted

encoder.dateEncodingStrategy = .custom({
    date, encoder in
    ...
})
// or
let formatter = DateFormatter()
formatter.dateFormat = "some format"
encoder.dateEncodingStrategy = .formatted(formatter)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多