使用Swift解码日期时出错 [英] Error Decoding Date with Swift

查看:738
本文介绍了使用Swift解码日期时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我的JSON如下:

For example my JSON looks like so:

{ 
   createdAt = "2018-06-13T12:38:22.987Z"  
}

My Struct看起来像这样:

My Struct looks like so:

struct myStruct {
    let createdAt: Date
}

解码如下:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

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

When I am decoding I get this error:


无法解码,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))

failed to decode, dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "results", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "createdAt", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))

据我所知,该字符串应该是ISO8601格式,但不是吗?

I understand it says that the string was expected to be ISO8601 formatted, but isn't it?

推荐答案

标准的ISO8601日期格式不包括小数秒,因此您需要使用自定义日期格式化程序来实现日期解码策略。

The standard ISO8601 date format doesn't include fractional seconds so you need to use a custom date formatter for the date decoding strategy.

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)

这篇关于使用Swift解码日期时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆