使用 Swift 解码日期时出错

far*_*han 2 json ios swift

例如我的 JSON 看起来像这样:

{ 
   createdAt = "2018-06-13T12:38:22.987Z"  
}
Run Code Online (Sandbox Code Playgroud)

我的结构看起来像这样:

struct myStruct {
    let createdAt: Date
}
Run Code Online (Sandbox Code Playgroud)

像这样解码:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
Run Code Online (Sandbox Code Playgroud)

当我解码时,我收到此错误:

解码失败,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 格式的,但不是吗?

rma*_*ddy 8

标准 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)
Run Code Online (Sandbox Code Playgroud)