Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Swift 4中解码小写和大写JSON键_Swift_Swift4_Jsondecoder - Fatal编程技术网

在Swift 4中解码小写和大写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) }

我有以下表示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)
} 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,不在一个编码密钥内。使用两个单独的编码键,或者编写自己的解码功能。