【发布时间】:2018-04-04 17:09:37
【问题描述】:
我正在经历一些项目并删除 JSON 解析框架,因为使用 Swift 4 似乎很简单。我遇到了这个奇怪的 JSON 返回,其中 Ints 和 Dates 返回为 Strings。
我查看了GrokSwift's Parsing JSON with Swift 4、Apple's website,但没有看到任何跳出的内容:改变类型。
Apple's example code 展示了如何更改键名,但我很难弄清楚如何更改键类型。
它是这样的:
{
"WaitTimes": [
{
"CheckpointIndex": "1",
"WaitTime": "1",
"Created_Datetime": "10/17/2017 6:57:29 PM"
},
{
"CheckpointIndex": "2",
"WaitTime": "6",
"Created_Datetime": "10/12/2017 12:28:47 PM"
},
{
"CheckpointIndex": "0",
"WaitTime": "8",
"Created_Datetime": "9/26/2017 5:04:42 AM"
}
]
}
我使用CodingKey 将字典键重命名为符合 Swift 的条目,如下所示:
struct WaitTimeContainer: Codable {
let waitTimes: [WaitTime]
private enum CodingKeys: String, CodingKey {
case waitTimes = "WaitTimes"
}
struct WaitTime: Codable {
let checkpointIndex: String
let waitTime: String
let createdDateTime: String
private enum CodingKeys: String, CodingKey {
case checkpointIndex = "CheckpointIndex"
case waitTime = "WaitTime"
case createdDateTime = "Created_Datetime"
}
}
}
这仍然给我留下了String,应该是Int 或Date。如何使用 Codable 协议将包含 Int/Date/Float 作为 String 的 JSON 返回转换为 Int/Date/Float?
【问题讨论】:
-
@Adrian 确保 Created_Datetime 存储到服务器时是 UTC 时间而不是本地时间,否则在解析日期时不应将日期格式化程序时区设置为零 secondsFromGMT。
标签: ios json swift swift4 codable