【发布时间】:2019-11-05 06:02:51
【问题描述】:
我有 JSON 响应,其中有“0”作为 JSON 的键值。我正在使用 Swift 的 Codable 协议来解析我的 JSON。有什么方法可以将“0”作为变量的名称或其他一些解决方法?我知道用于解析 JSON 的 SwiftyJSON,但我更喜欢使用本地 swift 协议。 This is my JSON response.
【问题讨论】:
我有 JSON 响应,其中有“0”作为 JSON 的键值。我正在使用 Swift 的 Codable 协议来解析我的 JSON。有什么方法可以将“0”作为变量的名称或其他一些解决方法?我知道用于解析 JSON 的 SwiftyJSON,但我更喜欢使用本地 swift 协议。 This is my JSON response.
【问题讨论】:
如果“0”键是常量,您可以使用CodingKeys 将其映射到有效的属性名称,如下所示:
struct Response: Codable {
let success: Bool
let data: DataClass
let error, message: String
}
struct ZeroKeyType: Codable {
// properties go here
}
struct DataClass: Codable {
let the0: ZeroKeyType
let searchField: [String]
enum CodingKeys: String, CodingKey {
case the0 = "0"
case searchField
}
}
【讨论】: