我有一个Codable结构myObj
public struct VIO: Codable {
let id:Int?;
...
var par1:Bool = false; //default to avoid error in parsing
var par2:Bool = false;
}当我收到JSON时,我没有par1和par2,因为这些变量是可选的。在解析过程中,我得到一个错误:keyNotFound(CodingKeys(stringValue: \"par1\", intValue: nil)
如何解决这个问题?
发布于 2018-04-07 16:35:39
如果有局部变量,则必须指定CodingKeys
public struct VIO: Codable {
private enum CodingKeys : String, CodingKey { case id }
let id:Int?
...
var par1:Bool = false
var par2:Bool = false
}编辑:
如果par1和par2也应该可选地解码,则必须编写自定义初始化程序。
private enum CodingKeys : String, CodingKey { case id, par1, par2 }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
par1 = try container.decodeIfPresent(Bool.self, forKey: .par1)
par2 = try container.decodeIfPresent(Bool.self, forKey: .par2)
}这是Swift:无尾随分号
https://stackoverflow.com/questions/49709518
复制相似问题