json - 如何将日期字符串从 JSON 解码为 Date 对象?
问题描述
如何将时间戳从 JSON 解码为日期?
我从服务器获取我的日期作为 Json,如下所示:
{
"date": "2610-02-16T03:16:15.143Z"
}
我试图从中构建一个 Date 类:
class Message : Decodable {
var date: Date
}
它没有按预期工作我收到此错误:
Failed to fetch messages: typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "date", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))
解决方案
像这样解码日期信息时,您需要使用自定义dateDecodingStrategy
,并设置日期解析器的时区和语言环境:
let data = """
{
"date": "2610-02-16T03:16:15.143Z"
}
""".data(using: .utf8)!
struct Message: Codable {
let date: Date
}
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(identifier: "GMT")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
do {
let message = try decoder.decode(Message.self, from: data)
print(message.date)
} catch {
print(erroor)
}
推荐阅读
- unit-testing - 酶:wrapper.find('SickButton').simulate('click') 没有点击
- regex - 谷歌表格:正则提取
- sql-server - 在 BeginTrans 之后立即 CommitTrans
- c# - 从 python 访问 System.Reflection.Pointer
- python - 为什么输入数组在递归函数内部会发生变化?
- python - 请问如何在python中绘制多重图?我尝试使用networkx库这样做,但只绘制了两个节点之间的一个连接
- javascript - Selenium-Web 驱动程序无法读取未定义的属性“过滤器”
- python - 在 python 中通过 telnet 发送十六进制值
- python - 计算两条无限线的二维交点
- c++ - 您可以在对象的生命周期开始之前创建对对象的引用,然后在没有未定义行为的情况下稍后使用它吗?