在Swift 4中解码小写和大写JSON键
我有以下表示JSON的结构:在Swift 4中解码小写和大写JSON键,swift,swift4,jsondecoder,Swift,Swift4,Jsondecoder,我有以下表示JSON的结构: struct Todo: Codable { let ID: Int? let LAST_DT_ADD: String? let LAST_ID:Int? } 当我用同样的方法解码时: let decoder = JSONDecoder() do { let todo = try decoder.decode(Todo.self, from: responseData) completionHandler(todo, nil) }
struct Todo: Codable {
let ID: Int?
let LAST_DT_ADD: String?
let LAST_ID:Int?
}
当我用同样的方法解码时:
let decoder = JSONDecoder()
do {
let todo = try decoder.decode(Todo.self, from: responseData)
completionHandler(todo, nil)
} catch {
print("error trying to convert data to JSON")
print(error)
completionHandler(nil, error)
}
它可以正确解码,但当我有小写的JSON项时(例如,不是
ID
,LAST\u-ID
和LAST\u-ID
,而是ID
,LAST\u-ID
),它就不会解码对象。我该怎么办?如何支持大写和小写?您应该在编码键
枚举中提供正确的版本作为关联值
enum CodingKeys: String, CodingKey {
case ID = "id"
case LAST_DT_ADD = "last_dt_add"
case LAST_ID = "last_id"
}
请注意,在Swift中,命名变量的约定在camelCase中是标准化的,而不是snake_case。当然,你是对的。但当我有大写的钥匙时?我可以在解码时支持大小写吗?@Dmitry No,不在一个编码密钥内。使用两个单独的编码键,或者编写自己的解码功能。