One way to create a custom decoding strategy in Swift that converts snake_case to camelCase and capitalizes the word id
is by creating a struct that conforms to the CodingKey
protocol and implementing the init
and stringValue
methods. Here's an example implementation:
main.swift1012 chars34 lines
To use this custom decoding strategy, you need to create a JSONDecoder
instance and set its keyDecodingStrategy
property to .custom
with a closure that returns the SnakeToCamelCaseCodingKey
for each key:
main.swift362 chars10 lines
Now, when you decode a JSON object with this JSONDecoder
instance, all keys in snake_case will be automatically converted to camelCase and the word id
will be capitalized:
main.swift387 chars18 lines
Note: This implementation assumes that all keys in the JSON object are in snake_case. If you also need to support keys in camelCase or other formats, you will need to modify the convertSnakeToCamelCase
method accordingly.
gistlibby LogSnag