2

我有以下表示 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_DT_ADDand LAST_ID,我有id, last_dt_addand last_id),它没有解码对象。我需要做什么?如何支持大写和小写?

4

1 回答 1

6

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

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

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

于 2018-01-31T09:59:32.953 回答