在Swift 4中解码小写和大写JSON密钥

德米特里

我有以下表示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项小写(例如代替IDLAST_DT_ADD并且LAST_ID,我有idlast_dt_addlast_id),则不是对象进行解码。我需要做什么?如何支持大写和小写?

塔玛斯·森格尔

您应该在CodingKeys枚举中提供正确的版本作为关联值

enum CodingKeys: String, CodingKey {
    case ID = "id"
    case LAST_DT_ADD = "last_dt_add"
    case LAST_ID = "last_id"
}

请注意,在Swift中,命名变量的约定是在camelCase中而不是snake_case中标准化的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章