Swift的JSONDecoder
提供了dateDecodingStrategy
属性,允许我们根据DateFormatter
对象定义如何解释传入的日期字符串。
但是,我目前正在使用一个返回日期字符串(yyyy-MM-dd
)和日期时间字符串(yyyy-MM-dd HH:mm:ss
)的API,具体取决于属性。有没有办法让JSONDecoder
处理这个,因为提供的DateFormatter
对象一次只能处理一个dateFormat
?
一个简单的解决方案是重写随附的Decodable
模型,只接受字符串作为其属性,并提供公共Date
getter / setter变量,但这对我来说似乎是一个糟糕的解决方案。有什么想法吗?
答案 0 :(得分:27)
请尝试与此类似的解码器配置:
lazy var decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
let container = try decoder.singleValueContainer()
let dateStr = try container.decode(String.self)
// possible date strings: "2016-05-01", "2016-07-04T17:37:21.119229Z", "2018-05-20T15:00:00Z"
let len = dateStr.count
var date: Date? = nil
if len == 10 {
date = dateNoTimeFormatter.date(from: dateStr)
} else if len == 20 {
date = isoDateFormatter.date(from: dateStr)
} else {
date = self.serverFullDateFormatter.date(from: dateStr)
}
guard let date_ = date else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(dateStr)")
}
print("DATE DECODER \(dateStr) to \(date_)")
return date_
})
return decoder
}()
答案 1 :(得分:26)
有几种方法可以解决这个问题:
DateFormatter
子类,它首先尝试日期时间字符串格式,然后如果失败,则尝试普通日期格式.custom
Date
解码策略,其中您向Decoder
询问singleValueContainer()
,解码字符串,并在传递之前将其传递给您想要的任何格式器解析日期Date
类型创建一个包装器,它提供自定义init(from:)
和encode(to:)
来执行此操作(但这并不比{{1更好)战略).custom
并尝试不同的内容总而言之,前两种方法可能是最简单,最干净的方法 - 您可以在任何地方保留init(from:)
的默认合成实现,而不会牺牲类型安全性。
答案 2 :(得分:14)
面对同样的问题,我写了以下扩展名:
extension JSONDecoder.DateDecodingStrategy {
static func custom(_ formatterForKey: @escaping (CodingKey) throws -> DateFormatter?) -> JSONDecoder.DateDecodingStrategy {
return .custom({ (decoder) -> Date in
guard let codingKey = decoder.codingPath.last else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "No Coding Path Found"))
}
guard let container = try? decoder.singleValueContainer(),
let text = try? container.decode(String.self) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date text"))
}
guard let dateFormatter = try formatterForKey(codingKey) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "No date formatter for date text")
}
if let date = dateFormatter.date(from: text) {
return date
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(text)")
}
})
}
}
此扩展允许您为JSONDecoder创建DateDecodingStrategy,以处理同一JSON字符串中的多种不同日期格式。扩展包含一个函数,该函数需要实现一个为您提供CodingKey的闭包,并且您可以为所提供的密钥提供正确的DateFormatter。
假设您有以下JSON:
{
"publication_date": "2017-11-02",
"opening_date": "2017-11-03",
"date_updated": "2017-11-08 17:45:14"
}
以下结构:
struct ResponseDate: Codable {
var publicationDate: Date
var openingDate: Date?
var dateUpdated: Date
enum CodingKeys: String, CodingKey {
case publicationDate = "publication_date"
case openingDate = "opening_date"
case dateUpdated = "date_updated"
}
}
然后要解码JSON,您将使用以下代码:
let dateFormatterWithTime: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
let dateFormatterWithoutTime: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom({ (key) -> DateFormatter? in
switch key {
case ResponseDate.CodingKeys.publicationDate, ResponseDate.CodingKeys.openingDate:
return dateFormatterWithoutTime
default:
return dateFormatterWithTime
}
})
let results = try? decoder.decode(ResponseDate.self, from: data)
答案 3 :(得分:8)
试试这个。 (迅速4)
let formatter = DateFormatter()
var decoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = formatter.date(from: dateString) {
return date
}
formatter.dateFormat = "yyyy-MM-dd"
if let date = formatter.date(from: dateString) {
return date
}
throw DecodingError.dataCorruptedError(in: container,
debugDescription: "Cannot decode date string \(dateString)")
}
return decoder
}
答案 4 :(得分:2)
使用单个编码器无法做到这一点。这里您最好的选择是自定义encode(to encoder:)
和init(from decoder:)
方法,并为这些值提供您自己的翻译,为另一个值留下内置日期策略。
为此目的,考虑将一个或多个格式化程序传递到userInfo
对象可能是值得的。
答案 5 :(得分:0)
如果您在单个模型中有多个不同格式的日期,则每个日期都难以应用.dateDecodingStrategy
。
点击此处https://gist.github.com/romanroibu/089ec641757604bf78a390654c437cb0获取方便的解决方案
答案 6 :(得分:0)
这有点冗长,但方法更灵活:用另一个Date类包装日期,并为其实现自定义序列化方法。例如:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
class MyCustomDate: Codable {
var date: Date
required init?(_ date: Date?) {
if let date = date {
self.date = date
} else {
return nil
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
let string = dateFormatter.string(from: date)
try container.encode(string)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(String.self)
if let date = dateFormatter.date(from: raw) {
self.date = date
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot parse date")
}
}
}
因此,您现在独立于.dateDecodingStrategy
和.dateEncodingStrategy
,并且您的MyCustomDate
日期将以指定的格式进行解析。在课堂上使用它:
class User: Codable {
var dob: MyCustomDate
}
实例化
user.dob = MyCustomDate(date)
答案 7 :(得分:0)
快速5
实际上基于@BrownsooHan版本,使用扩展名JSONDecoder
JSONDecoder + dateDecodingStrategyFormatters.swift
extension JSONDecoder {
/// Assign multiple DateFormatter to dateDecodingStrategy
///
/// Usage :
///
/// decoder.dateDecodingStrategyFormatters = [ DateFormatter.standard, DateFormatter.yearMonthDay ]
///
/// The decoder will now be able to decode two DateFormat, the 'standard' one and the 'yearMonthDay'
///
/// Throws a 'DecodingError.dataCorruptedError' if an unsupported date format is found while parsing the document
var dateDecodingStrategyFormatters: [DateFormatter]? {
@available(*, unavailable, message: "This variable is meant to be set only")
get { return nil }
set {
guard let formatters = newValue else { return }
self.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
for formatter in formatters {
if let date = formatter.date(from: dateString) {
return date
}
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(dateString)")
}
}
}
}
添加只能设置的变量有点麻烦,但是您可以轻松地将var dateDecodingStrategyFormatters
转换为func setDateDecodingStrategyFormatters(_ formatters: [DateFormatter]? )
用法
让我们说您已经在代码中定义了多个DateFormatter
,如下所示:
extension DateFormatter {
static let standardT: DateFormatter = {
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return dateFormatter
}()
static let standard: DateFormatter = {
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
static let yearMonthDay: DateFormatter = {
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
}
您现在可以通过设置dateDecodingStrategyFormatters
直接将它们分配给解码器:
// Data structure
struct Dates: Codable {
var date1: Date
var date2: Date
var date3: Date
}
// The Json to decode
let jsonData = """
{
"date1": "2019-05-30 15:18:00",
"date2": "2019-05-30T05:18:00",
"date3": "2019-04-17"
}
""".data(using: .utf8)!
// Assigning mutliple DateFormatters
let decoder = JSONDecoder()
decoder.dateDecodingStrategyFormatters = [ DateFormatter.standardT,
DateFormatter.standard,
DateFormatter.yearMonthDay ]
do {
let dates = try decoder.decode(Dates.self, from: jsonData)
print(dates)
} catch let err as DecodingError {
print(err.localizedDescription)
}
边注
再一次,我知道将dateDecodingStrategyFormatters
设置为var
有点麻烦,我不建议这样做,而应该定义一个函数。但是,这样做是个人喜好。