Created
November 18, 2024 17:18
-
-
Save eneko/2d595bf044180fcb9b54a04694659835 to your computer and use it in GitHub Desktop.
Codable with snake_case conversion gotcha
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// If you work with Codable and use automatic `snake_case` conversion | |
/// when encoding/decoding objects, you might have found that `fooId` | |
/// works both ways, however `fooID` does not. | |
/// | |
/// Issue: decoder fails to convert `snake_id` to `snakeID` | |
/// | |
import Foundation | |
struct Snake: Codable { | |
var snakeID: UUID | |
var name: String | |
} | |
let encoder = JSONEncoder() | |
encoder.keyEncodingStrategy = .convertToSnakeCase | |
let decoder = JSONDecoder() | |
decoder.keyDecodingStrategy = .convertFromSnakeCase | |
do { | |
let snake = Snake(snakeID: UUID(), name: "Foo Snake") | |
let data = try encoder.encode(snake) | |
let decoded = try decoder.decode(Snake.self, from: data) | |
} catch { | |
dump(error) | |
} | |
/// Error output: | |
/// ``` | |
/// ▿ Swift.DecodingError.keyNotFound | |
/// ▿ keyNotFound: (2 elements) | |
/// - .0: CodingKeys(stringValue: "snakeID", intValue: nil) | |
/// ▿ .1: Swift.DecodingError.Context | |
/// - codingPath: 0 elements | |
/// - debugDescription: "No value associated with key CodingKeys(stringValue: \"snakeID\", intValue: nil) (\"snakeID\")." | |
/// - underlyingError: nil | |
/// ``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment