2

I have the following struct that represents a JSON:

struct Todo: Codable {
    let ID: Int?
    let LAST_DT_ADD: String?
    let LAST_ID:Int?
}

And when I use decode the same way:

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)
}

It decodes correctly, but when I have JSON items in lowercase (for example instead of ID, LAST_DT_ADD and LAST_ID, I have id, last_dt_add and last_id), it is not decoding the object. What do I have to do? How can I support uppercase and lowercase?

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Dmitry
  • 125
  • 2
  • 9

1 Answers1

6

You should provide the correct version as an associated value in your CodingKeys enum.

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

Please note that in Swift, the convention for naming variables is standardized in camelCase and not snake_case.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • 2
    sure, you are right. But when i have key in uppercase? Can i support uppercase and lowercase in decoding? – Dmitry Jan 31 '18 at 10:03
  • @Dmitry No, not within one coding key. Use two separate coding keys for that or write your own decoding function. – Tamás Sengel Jan 31 '18 at 10:04