我正在研究一些项目和删除JSON解析框架,因为使用Swift 4似乎非常简单,我遇到了这个奇怪的JSON返回,其中Ints和Dates作为Strings返回。
我看了一下GrokSwift用Swift 4解析JSON,苹果网站,但是我没有看到任何跳出的东西:改变类型。
苹果的示例代码展示了如何更改密钥名,但我很难弄清楚如何更改密钥类型。
看上去是这样的:
{
    "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。如何使用可编码协议将包含Int/Date/Float作为String的JSON返回转换为Int/Date/Float?
发布于 2017-10-24 03:55:28
public extension KeyedDecodingContainer {
public func decode(_ type: Date.Type, forKey key: Key) throws -> Date {
    let dateString = try self.decode(String.self, forKey: key)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss a"
    guard let date = dateFormatter.date(from: dateString) else {
        let context = DecodingError.Context(codingPath: codingPath,
                                            debugDescription: "Could not parse json key to a Date")
        throw DecodingError.dataCorrupted(context)
    }
    return date
}
}用途:-
let date: Date = try container.decode(Date.self, forKey: . createdDateTime)https://stackoverflow.com/questions/46901445
复制相似问题