With Swift's JSONDecoder, how do CodingKeys and the .convertFromSnakeCase key strategy map snake_case keys, and why does combining them often throw keyNotFound?
answer
- two places a key can change
- the strategy rewrites JSON keys first
- acronyms do not survive capitalization
- raw values must match converted keys
basics
~20 sCodingKeys raw values rename or skip properties; .convertFromSnakeCase rewrites each JSON key to camelCase before matching them. Combined, a raw value like "user_id" or a property named imageURL no longer matches the converted key, so decoding throws keyNotFound.
solid answer
~40 sA hand-written `CodingKeys` enum names the properties to code and, through raw values, the exact JSON key for each: `case stationID = "station_id"`. `JSONDecoder.keyDecodingStrategy = .convertFromSnakeCase` works earlier: it rewrites every JSON key, capitalizing each word after an underscore and dropping the underscores, then matches the result against the `CodingKeys` string values. So `image_url` becomes `imageUrl`, which does not match a property named `imageURL`, and a raw value of `"user_id"` never matches the converted `userId`; both throw `keyNotFound`. Pick one discipline: with the strategy on, write raw values in converted form (`"imageUrl"`); with it off, spell the snake_case keys. Leaving a property out of `CodingKeys` skips it, but it then needs a default value.
code
swift · 18 linesimport Foundation
struct Station: Decodable {
let stationID: String
let imageURL: URL
let elevationM: Int
enum CodingKeys: String, CodingKey {
case stationID = "stationId" // "station_id" after conversion
case imageURL = "imageUrl" // "image_url" after conversion
case elevationM // "elevation_m" after conversion
}
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let json = #"{"station_id": "OSL", "image_url": "https://example.com/osl.png", "elevation_m": 94}"#
print(try decoder.decode(Station.self, from: Data(json.utf8)))go deeper
Recall that CodingKeys raw values rename JSON keys and that leaving a property out of CodingKeys skips it.
Explain the order of operations: the strategy rewrites JSON keys first, then the converted keys are matched against CodingKeys string values.
Spot the mixed setup in review, snake_case raw values on a converting decoder or acronym properties, and ask for a decode test against a recorded payload.
Set one team convention per API, strategy on with camelCase raw values or strategy off with explicit keys, so the mistake cannot recur model by model.
## Two tools for one problem A weather API that sends `station_id`, `image_url` and `elevation_m` does not match Swift's camelCase property names. Swift gives you two ways to bridge that gap, and they work at different points of the decode. - **`CodingKeys` raw values** live in the type. A hand-written `enum CodingKeys: String, CodingKey` lists the properties to code and, through each case's raw value, the exact key to look for: `case stationID = "station_id"`. - **`JSONDecoder.keyDecodingStrategy`** lives on the decoder. Set to `.convertFromSnakeCase`, it rewrites every key **in the JSON** before any type looks at it. The default is `.useDefaultKeys`, which leaves keys alone. ## What `.convertFromSnakeCase` actually does The doc comment in swift-foundation describes three steps: 1. capitalize the word that starts after each `_`; 2. remove every `_`; 3. keep leading and trailing underscores, so `_one_two_three_` becomes `_oneTwoThree_`. The capitalization uses `capitalized` on each word, so `image_url` becomes `imageUrl`, never `imageURL`, and `station_id` becomes `stationId`. A key with no underscore is left exactly as it is. If two JSON keys convert to the same name, the implementation keeps the first one it saw. The doc also notes that a key strategy other than `.useDefaultKeys` may cost some performance, because every key is inspected. ## Why combining them throws `keyNotFound` The strategy changes the JSON keys; it does **not** change your `CodingKeys`. Matching then compares the converted JSON key with each case's string value, character for character. | Swift declaration | JSON key | Converted key | Result | |---|---|---|---| | `let imageURL: URL`, no `CodingKeys` | `image_url` | `imageUrl` | `keyNotFound` for `imageURL` | | `case userID = "user_id"` | `user_id` | `userId` | `keyNotFound` for `user_id` | | `case userID = "userId"` | `user_id` | `userId` | decodes | | `let elevationM: Int` | `elevation_m` | `elevationM` | decodes | So pick one discipline per decoder: - **Strategy on**: write `CodingKeys` raw values in the converted camelCase form (`"imageUrl"`), only for properties whose Swift name differs from the conversion, such as acronyms. - **Strategy off**: spell the snake_case key in every raw value (`"image_url"`) and keep the decoder at `.useDefaultKeys`. Mixing them, with snake_case raw values on a converting decoder, is the classic bug: the type looks right in review and fails only at run time. ## Renaming and skipping with `CodingKeys` Writing `CodingKeys` by hand replaces the synthesized one, and two rules follow: - every case must match a stored property, or synthesis fails with a note that the `CodingKey` case does not match any stored properties; - a stored property you leave out is skipped in both directions, but it must have a default value, or the note reads "does not have a matching CodingKey and does not have a default value". A `var` of `Optional` type counts, because it defaults to `nil`; a `let` of `Optional` type with no initial value does not. Skipping is how a model keeps local-only state, such as a cached image or a selection flag, out of the wire format. ## When converted keys collide Conversion can map two JSON keys to one name: a payload carrying both `user_id` and `userId` produces `userId` twice. The decoder keeps the **first** value it meets in the object and drops the other, and its source comment calls this effectively undefined behaviour for JSON objects. No error is thrown, so the wrong value can be decoded silently. If an API mixes naming styles, prefer `.useDefaultKeys` with explicit raw values, or a `.custom` key strategy that you can test against every key the server sends. The `.custom` strategy receives the full coding path, so it can treat keys differently by depth, for example leaving the keys of a free-form dictionary untouched. A `[String: T]` dictionary, by contrast, is exempt: `JSONDecoder` leaves its keys exactly as the server sent them, so `{"by_station": {"north_gate": 1}}` decodes into a `byStation` property whose dictionary key is still `north_gate`. Only keys that are matched against a `CodingKey` are converted. ## The round trip trap `JSONEncoder` has the mirror strategy, `keyEncodingStrategy = .convertToSnakeCase`, which turns `imageURL` into `image_url`. Decoding that output with `.convertFromSnakeCase` yields `imageUrl`, which no longer matches `imageURL`. A type with acronym property names therefore does not round-trip through the paired strategies unless `CodingKeys` pins the name, which is worth a unit test whenever you cache API payloads to disk.
- How does `.convertFromSnakeCase` treat a key such as `_links` or `etag`?Leading and trailing underscores are preserved, so `_links` stays `_links`, and a key with no inner underscore is left unchanged, so `etag` must match a property spelled `etag`. Only the underscores between words are removed, with the following word capitalized.
- Why does a model encoded with `.convertToSnakeCase` sometimes fail to decode with `.convertFromSnakeCase`?The two conversions are not inverses for acronyms. `imageURL` encodes as `image_url`, which decodes to `imageUrl`, so the `imageURL` key is not found. Pin such properties with a `CodingKeys` raw value in converted form, `"imageUrl"`, and cover the round trip with a test.
- When would you choose a `.custom` key decoding strategy instead?When the server's naming scheme is not snake_case, for example keys with a prefix or kebab-case. The `.custom` closure receives the coding path and returns the `CodingKey` to use for the last component, so one function can normalize every key. It runs for every key of every object decoded through a keyed container, so keep it cheap.
- With .convertFromSnakeCase, CodingKeys raw values should keep the original snake_case spelling.
- The key strategy converts image_url to imageURL.
- CodingKeys raw values bypass the decoder's key strategy.
- A property left out of CodingKeys is decoded under its own name anyway.
- convertToSnakeCase and convertFromSnakeCase always round-trip a property name.