【问题标题】:Is it possible yet to use Decodable with Firestore Timestamps/Dates?是否可以将 Decodable 与 Firestore 时间戳/日期一起使用?
【发布时间】:2019-04-29 19:53:36
【问题描述】:

我有一个字典,它是 [String: Bookmark],但 createdAt 保存为 Timestamp,解码器在尝试理解 Date 时抛出错误

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“JSON 写入 (__NSDate) 中的类型无效”

struct Bookmark: Decodable {
    let messageId: String
    let messageCreatedAt: Date
}


JSONDecoder().decode([String: Bookmark].self, data: data)

有没有办法让 Swift 的 Decodable 协议与 Firestore 时间戳很好地配合?

编辑:

如果我打印 [String: Any] 然后尝试像这样在控制台中解码

 ▿ 1 : 2 elements
    - key : "messageCreatedAt"
    - value : 2018-11-27 20:59:11 +0000

po valueDict["messageCreatedAt"] as? Date

我明白了

▿ Optional<Date>
  ▿ some : 2018-11-27 20:59:11 +0000
    - timeIntervalSinceReferenceDate : 565045151.531769

那么它一定是Decodable 中的某些东西,那么它无法识别和解析它?

编辑:

JSON 是

{
  "messageId": "abc123",
  "messageCreatedAt": "2018-11-27 20:59:11 +0000"
}

【问题讨论】:

  • 请在问题中添加您尝试解析的 JSON。
  • @user28434 添加了 json
  • 已修复。日期在引号中
  • 已修复。 json 来自 firestore,而不是一个人创建的 fwiw

标签: ios swift firebase google-cloud-firestore


【解决方案1】:

JSONDecoder 如何解码日期由.dateDecodingStrategy 属性的值定义。

如果您必须从字符串中解析Date,您应该使用.iso8601.formatted(_:)(或者如果您的日期格式非常自定义、复杂和/或奇怪,您可能会使用.custom(_:))。

您的日期字符串几乎是ISO 8601 格式的(它只在日期和时间部分之间缺少T),但这足以失败。

所以你最好的选择是使用formatted(_:):

// Declare it somewhere and reuse single instance as much as possible, formatter initialization is quite expensive
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // Better to fix Locale here
dateFormatter.dateFormat = "yyyy-MM-dd kk:mm:ss Z"

然后

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let bookmark = try decoder.decode(Bookmark.self, from: data) 

print(bookmark.messageCreatedAt, bookmark.messageCreatedAt.timeIntervalSince1970)
// prints "2018-11-27 20:59:11 +0000 1543352351.0"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 2019-10-09
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多