gpt4 book ai didi

json - 在 Swift 中从 String 或 TimeInterval 解码日期/时间

转载 作者:行者123 更新时间:2023-12-05 09:36:50 25 4
gpt4 key购买 nike

我有一个 JSON(来自第三方)需要解析。此 JSON 返回多个嵌套对象

articles: {
authors: {
birthday: 'DD-MM-YYYY'
}
relevant_until: 'YYYY-MM-DD HH:MM:SS'
publication_date: secondsSince1970,
last_comment: iso8601
}

我正在关注 this answer拥有多个日期格式化程序并且它可以工作,只要从 JSON 中提取的每个日期都是一个字符串。

但是当涉及到 secondsSince1970(UNIX epoc 时间)时,我找不到将其解析为可编码对象的方法。我到处都看到 Date(timeIntervalSince1970: timestamp) 但我不知道如何在解码时使用它

当日期可以作为 TimeInterval 或字符串传递时,如何解析此对象上的日期?

try jsonDecoder.decode(Articles.self, from: jsonData)

最佳答案

extension Formatter {
static let iso8601withFractionalSeconds: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
static let ddMMyyyy: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd-MM-yyyy"
return formatter
}()
}

extension JSONDecoder.DateDecodingStrategy {
static let multiple = custom {
let container = try $0.singleValueContainer()
do {
return try Date(timeIntervalSince1970: container.decode(Double.self))
} catch DecodingError.typeMismatch {
let string = try container.decode(String.self)
if let date = Formatter.iso8601withFractionalSeconds.date(from: string) ??
Formatter.iso8601.date(from: string) ??
Formatter.ddMMyyyy.date(from: string) {
return date
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(string)")
}
}
}

Playground 测试:

struct Root: Codable {
let articles: Articles
}
struct Articles: Codable {
let authors: Authors
let relevantUntil: Date
let publicationDate: Date
let lastComment: Date
}

struct Authors: Codable {
let birthday: Date
}

let json = """
{"articles": {
"authors": {"birthday": "01-01-1970"},
"relevant_until": "2020-11-19 01:23:45",
"publication_date": 1605705003.0019,
"last_comment": "2020-11-19 01:23:45.678"}
}
"""

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .multiple
decoder.keyDecodingStrategy = .convertFromSnakeCase

do {
let root = try decoder.decode(Root.self, from: .init(json.utf8))
print(root.articles) // Articles(authors: __lldb_expr_107.Authors(birthday: 1970-01-01 03:00:00 +0000), relevantUntil: 2020-11-19 04:23:45 +0000, publicationDate: 2020-11-18 13:10:03 +0000, lastComment: 2020-11-19 04:23:45 +0000)

} catch {
print(error)
}

关于json - 在 Swift 中从 String 或 TimeInterval 解码日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64892897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com