I'd like to highlight to the community one counterintuitive, in my opinion, behaviour of JSONDecoder used with key decoding strategy. Imagine I have a type of a person defined like this:
struct Person: Codable {
let firstName: String
let surname: String
}
My API follows a snake-case notation for key so I'm going to use convertFromSnakeCase
key decoding strategy. But for whatever reason, let's say historical, surname is returned by the API by last_name
key. So I go and define custom coding keys:
struct Person: Codable {
let firstName: String
let surname: String
enum CodingKeys: String, CodingKey {
case firstName
case surname = "last_name"
}
I only define custom key hoping that key decoding strategy will figure out other keys in runtime.
Then I go and try to decode json that looks like this:
{
"first_name" : "Ilya",
"last_name" : "Puchka"
}
This does not work though and fails with an error "No value associated with key last_name". This is first, in my opinion, misleading thing - the error says that there is no data for a key that is clearly there.
The decoding works only when I change my custom coding key's raw value to the value that is a result of a transformation applied by key decoding strategy to the corresponding json key. So in this case - "lastName"
enum CodingKeys: String, CodingKey {
case firstName
case surname = "lastName"
}
Which is the second counterintuitive thing here, as I would expect the raw value of the key to be the raw value of json key, not some transformed string.
Can it be considered a bug or a shortcoming of current implementation, or is it my understanding of keys decoding strategies which is wrong?