我正在经历一些项目并删除 JSON 解析框架,因为使用 Swift 4 似乎很简单。我遇到了这个奇怪的 JSON return where Ints
and Dates
are returned as Strings
.
我查看了GrokSwift 的 Parsing JSON with Swift 4,Apple 的网站,但我没有看到任何跳出来的东西:改变类型。
Apple 的示例代码显示了如何更改键名,但我很难弄清楚如何更改键类型。
这是它的样子:
{
"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
or Date
。我将如何使用 Codable 协议将包含Int/Date/Float
as a的 JSON 返回转换String
为 an ?Int/Date/Float