使用编码键排除被解码的值
Using Coding Keys to exclude values from being decoded
我有以下结构来解码JSON数据:
更新:
struct Section {
let owner : String
var items : [ValueVariables]
}
struct ValueVariables : Decodable {
var isSelected = false
let breed: String
let color: String
let tagNum: Int
// other members
}
问题是isSelected
不是被解码的值,我怎样才能排除它被解码以防止它导致这样的错误:
keyNotFound(CodingKeys(stringValue: "isSelected", intValue: nil),
Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index
0", intValue: 0)], debugDescription: "No value associated with key
CodingKeys(stringValue: \"isSelected\", intValue: nil)
(\"isSelected\"), converted to is_selected.", underlyingError: nil))
我试过像这样使用编码键,但它似乎不起作用:
private enum CodingKeys : String, CodingKey {
case isSelected = "isSelected"
}
应用答案:
struct ValueVariables : Decodable {
private enum CodingKeys : String, CodingKey {
case breed, color, tagNum
}
var isSelected = false
let breed: String
let color: String
let tagNum: Int
}
JSON看起来像这样:
[{"breed":"dog","color":"black","tagNum":20394}]
收到错误:
Type 'ValueVariables' does not conform to protocol 'Decodable'
反之,您必须指定要解码的所有密钥。
struct ValueVariables : Decodable {
private enum CodingKeys : String, CodingKey {
case breed, color
}
var isSelected = false
let breed: String
let color: String
}
我有以下结构来解码JSON数据:
更新:
struct Section {
let owner : String
var items : [ValueVariables]
}
struct ValueVariables : Decodable {
var isSelected = false
let breed: String
let color: String
let tagNum: Int
// other members
}
问题是isSelected
不是被解码的值,我怎样才能排除它被解码以防止它导致这样的错误:
keyNotFound(CodingKeys(stringValue: "isSelected", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"isSelected\", intValue: nil) (\"isSelected\"), converted to is_selected.", underlyingError: nil))
我试过像这样使用编码键,但它似乎不起作用:
private enum CodingKeys : String, CodingKey {
case isSelected = "isSelected"
}
应用答案:
struct ValueVariables : Decodable {
private enum CodingKeys : String, CodingKey {
case breed, color, tagNum
}
var isSelected = false
let breed: String
let color: String
let tagNum: Int
}
JSON看起来像这样:
[{"breed":"dog","color":"black","tagNum":20394}]
收到错误:
Type 'ValueVariables' does not conform to protocol 'Decodable'
反之,您必须指定要解码的所有密钥。
struct ValueVariables : Decodable {
private enum CodingKeys : String, CodingKey {
case breed, color
}
var isSelected = false
let breed: String
let color: String
}