【发布时间】:2020-08-09 12:33:23
【问题描述】:
情况
我正在处理具有多个日期字段的 API 服务器,并且我发现这些日期字段的 API 响应可以是:
{
"clicktimestamp": "",
"clicktimestamp": " ",
"clicktimestamp": "2020-08-08 16:13:17"
}
JSON 响应可能是:
• 字符串(无空格)
• 字符串(带空格)
• 某些日期格式的字符串。
我无权访问 API 服务器,也无法要求服务器端工程师更改它。我的情况并不理想,所以我必须处理它。
可行的解决方案(不是很迅速)
我写了一些代码来处理这种情况。它可以工作,但 它的某些方面感觉不是很 Swift。
考虑到我的 JSON 响应情况,如何改进整个解码过程?
还是很好?
这是一个可行的解决方案:
import UIKit
import Foundation
struct ProductDate: Decodable, Hashable {
var lastcheckedtime: Date?
var oktime: Date?
var clicktimestamp: Date?
var lastlocaltime: Date?
// I have more properties but I'm omitting them
}
extension ProductDate {
private enum Keys: String, CodingKey {
case lastcheckedtime
case oktime
case clicktimestamp
case lastlocaltime
}
init(from decoder: Decoder) throws {
let formatter = DateFormatter.yyyyMMdd
let container = try decoder.container(keyedBy: Keys.self)
let dateKeys: [KeyedDecodingContainer<Keys>.Key] = [
.lastcheckedtime,
.oktime,
.clicktimestamp,
.lastlocaltime
]
let parseDate: (String, KeyedDecodingContainer<Keys>.Key, KeyedDecodingContainer<Keys>) throws -> Date? = {(dateString, someKey, container) in
if !dateString.isEmpty {
if let date = formatter.date(from: dateString) {
return date
} else {
throw DecodingError.dataCorruptedError(forKey: someKey,
in: container,
debugDescription: "Date string does not match format expected by formatter.")
}
} else {
return nil
}
}
let datesResults: [Date?] = try dateKeys.map({ key in
// 1. decode as a string because we sometimes get "" or " " for those date fields as the API server is poorly managed.
let dateString = try container.decode(String.self, forKey: key)
.trimmingCharacters(in: .whitespaces)
// 2. now pass in our dateString which could be "" or " " or "2020-08-08 16:13:17"
// and try to parse it into a Date or nil
let result = try parseDate(dateString, key, container)
return result
})
// 3. Assign our array of dateResults to our struct keys
lastcheckedtime = datesResults[0]
oktime = datesResults[1]
clicktimestamp = datesResults[2]
lastlocaltime = datesResults[3]
}
}
extension DateFormatter {
static let yyyyMMdd: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-DD HH:mm:ss"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
let json = """
{
"lastcheckedtime": "",
"oktime": " ",
"clicktimestamp": "",
"lastlocaltime": "2020-08-08 16:13:17"
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
print(json)
do {
let decoded = try decoder.decode(ProductDate.self, from: json)
print(decoded)
} catch let context {
print(context)
}
【问题讨论】:
-
您应该始终在设置 dateFormat 之前设置区域设置。您确定日期字符串是 UTC 吗?通常应将没有时区信息的日期字符串视为本地时间。
标签: json swift string codable decodable