Skip to content

Commit

Permalink
Add snakeCase JSON encoder and decoder for convenience
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeehut committed Nov 17, 2024
1 parent 15a51c5 commit 49dc8d5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Sources/HandySwift/Extensions/JSONDecoderExt.swift
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
}
}
21 changes: 21 additions & 0 deletions Sources/HandySwift/Extensions/JSONEncoderExt.swift
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
}
}

0 comments on commit 49dc8d5

Please sign in to comment.