使用Swift解码日期时出错
例如,我的JSON看起来像这样:
{ createdAt = "2018-06-13T12:38:22.987Z" }
我的结构看起来像这样:
struct myStruct { let createdAt: Date }
解码如下:
let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601
当我解码时,我收到此错误:
无法解码,dataCorrupted(Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“results”,intValue:nil),_ JSONKey(stringValue:“Index 0”,intValue:0),CodingKeys(stringValue:“createdAt”, intValue:nil)],debugDescription:“预期日期字符串为ISO8601格式。”,underlyingError:nil))
据我所知,该字符串预计将采用ISO8601格式,但不是吗?
标准ISO8601日期格式不包括小数秒,因此您需要使用自定义日期格式化程序来进行日期解码策略。
let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(dateFormatter)