Search code examples
swiftswift4jsondecoder

Decode lowercase and uppercase JSON keys in Swift 4


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?


Solution

  • 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.