使用swift4进行iso8601日期json解码 [英] iso8601 date json decoding using swift4
问题描述
所以,我的 json 中有 iso8601 日期,看起来像2016-06-07T17:20:00.000+02:00"
So, I've got iso8601 dates in my json which look like "2016-06-07T17:20:00.000+02:00"
有没有办法使用 swift4 解析这些 iso8601 日期?我是否遗漏了一些明显的东西?
Is there a way to parse these iso8601 dates using swift4? Am I missing something obvious?
我尝试了以下操作,但只有来自 jsonShipA 的 dateString "2016-06-07T17:20:00Z" 是可解析的....
I tried the following, but only the dateString "2016-06-07T17:20:00Z" from jsonShipA is parsable....
import Foundation
struct Spaceship : Codable {
var name: String
var createdAt: Date
}
let jsonShipA = """
{
"name": "Skyhopper",
"createdAt": "2016-06-07T17:20:00Z"
}
"""
let jsonShipB = """
{
"name": "Skyhopper",
"createdAt": "2016-06-07T17:20:00.000+02:00"
}
"""
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let dataA = jsonShipA.data(using: .utf8)!
if let decodedShip = try? decoder.decode(Spaceship.self, from: dataA) {
print("jsonShipA date = \(decodedShip.createdAt)")
} else {
print("Failed to decode iso8601 date format from jsonShipA")
}
let dataB = jsonShipB.data(using: .utf8)!
if let decodedShip = try? decoder.decode(Spaceship.self, from: dataB) {
print("jsonShipA date = \(decodedShip.createdAt)")
} else {
print("Failed to decode iso8601 date format from jsonShipB")
}
playground 的输出是:
The output of the playground is:
jsonShipA date = 2016-06-07 17:20:00 +0000
Failed to decode iso8601 date format from jsonShipB
抛出的错误是预期日期字符串为 ISO8601 格式."但据我所知,日期2016-06-07T17:20:00.000+02:00"是一个有效的 ISO8601 日期
The error being thrown is "Expected date string to be ISO8601-formatted." But to my knowledge, the date "2016-06-07T17:20:00.000+02:00" is a valid ISO8601 date
推荐答案
你可以这样使用:
enum DateError: String, Error {
case invalidDate
}
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
let container = try decoder.singleValueContainer()
let dateStr = try container.decode(String.self)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
if let date = formatter.date(from: dateStr) {
return date
}
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
if let date = formatter.date(from: dateStr) {
return date
}
throw DateError.invalidDate
})
这篇关于使用swift4进行iso8601日期json解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!