-
-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
snakeCase
JSON encoder and decoder for convenience
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import Foundation | ||
|
||
extension JSONDecoder { | ||
/// A pre-configured JSONDecoder that automatically converts snake_case JSON property names | ||
/// to camelCase when decoding into Swift types | ||
/// | ||
/// This decoder handles incoming JSON with snake_case keys and converts them to match | ||
/// Swift's camelCase property naming convention. | ||
/// | ||
/// Example usage: | ||
/// ``` | ||
/// let jsonString = """ | ||
/// { | ||
/// "first_name": "John", | ||
/// "last_name": "Doe" | ||
/// } | ||
/// """ | ||
/// let user = try JSONDecoder.snakeCase.decode(User.self, from: jsonData) | ||
/// // Results in: User(firstName: "John", lastName: "Doe") | ||
/// ``` | ||
static var snakeCase: JSONDecoder { | ||
let decoder = JSONDecoder() | ||
decoder.keyDecodingStrategy = .convertFromSnakeCase | ||
return decoder | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import Foundation | ||
|
||
extension JSONEncoder { | ||
/// A pre-configured JSONEncoder that automatically converts Swift's camelCase property names | ||
/// to snake_case when encoding JSON | ||
/// | ||
/// Instead of creating a new encoder and configuring it each time, this provides a ready-to-use | ||
/// encoder with snake_case conversion. | ||
/// | ||
/// Example usage: | ||
/// ``` | ||
/// let user = User(firstName: "John", lastName: "Doe") | ||
/// let jsonData = try JSONEncoder.snakeCase.encode(user) | ||
/// // Results in: {"first_name": "John", "last_name": "Doe"} | ||
/// ``` | ||
static var snakeCase: JSONEncoder { | ||
let encoder = JSONEncoder() | ||
encoder.keyEncodingStrategy = .convertToSnakeCase | ||
return encoder | ||
} | ||
} |