Funny that this came up pretty much right after I posted Handling edge cases in JSONEncoder/JSONDecoder key conversion strategies (SR-6629). This is a good data point for discussing the topic, I think.
What you're seeing here is a combination of two things:
- The raw value of the key is affected by the key strategy. Anything consuming a
CodingKey
can only operate on itsstringValue
/intValue
; there's no way for it to know that these values are being provided directly vs. being synthesized. As far asJSONEncoder
/JSONDecoder
is concerned, there's no difference betweencase last_name
andcase surname = "last_name"
, because there's no way for it to discern the difference - The behavior on decode with the key decoding strategy is described in the linked thread — when you
decode(String.self, forKey: .surname)
, the key in the JSON ("last_name"
) is converted to camelCase based on the.keyDecodingStrategy
, and the string value of.surname
("last_name"
) is used to look up the value. Because the JSON payload has already been converted to camelCase"last_name"
isn't found. Instead, you have to provide the camelCase name
(1) here happens by design (this is the idea behind the key strategy), but we're looking to improve on (2). Please take a look at the linked thread if you get a chance; I'd value your feedback there.