07-18-2023, 03:27 PM
I am replacing my old JSON parsing code with Swift's Codable and am running into a bit of a snag. I guess it isn't as much a Codable question as it is a DateFormatter question.
**Start with a struct**
struct JustADate: Codable {
var date: Date
}
**and a json string**
let json = """
{ "date": "2017-06-19T18:43:19Z" }
"""
**now lets decode**
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let data = json.data(using: .utf8)!
let justADate = try! decoder.decode(JustADate.self, from: data) //all good
But if we change the date so that it has fractional seconds, for example:
let json = """
{ "date": "2017-06-19T18:43:19.532Z" }
"""
Now it breaks. The dates sometimes come back with fractional seconds and sometimes do not. The way I used to solve it was in my mapping code I had a transform function that tried both dateFormats with and without the fractional seconds. I am not quite sure how to approach it using Codable however. Any suggestions?
**Start with a struct**
struct JustADate: Codable {
var date: Date
}
**and a json string**
let json = """
{ "date": "2017-06-19T18:43:19Z" }
"""
**now lets decode**
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let data = json.data(using: .utf8)!
let justADate = try! decoder.decode(JustADate.self, from: data) //all good
But if we change the date so that it has fractional seconds, for example:
let json = """
{ "date": "2017-06-19T18:43:19.532Z" }
"""
Now it breaks. The dates sometimes come back with fractional seconds and sometimes do not. The way I used to solve it was in my mapping code I had a transform function that tried both dateFormats with and without the fractional seconds. I am not quite sure how to approach it using Codable however. Any suggestions?