From 49dc8d5d990103ea71d4a090ace1794def327312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cihat=20Gu=CC=88ndu=CC=88z?= Date: Sun, 17 Nov 2024 12:59:46 +0100 Subject: [PATCH] Add `snakeCase` JSON encoder and decoder for convenience --- .../Extensions/JSONDecoderExt.swift | 26 +++++++++++++++++++ .../Extensions/JSONEncoderExt.swift | 21 +++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 Sources/HandySwift/Extensions/JSONDecoderExt.swift create mode 100644 Sources/HandySwift/Extensions/JSONEncoderExt.swift diff --git a/Sources/HandySwift/Extensions/JSONDecoderExt.swift b/Sources/HandySwift/Extensions/JSONDecoderExt.swift new file mode 100644 index 0000000..2088f16 --- /dev/null +++ b/Sources/HandySwift/Extensions/JSONDecoderExt.swift @@ -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 + } +} diff --git a/Sources/HandySwift/Extensions/JSONEncoderExt.swift b/Sources/HandySwift/Extensions/JSONEncoderExt.swift new file mode 100644 index 0000000..a3b0431 --- /dev/null +++ b/Sources/HandySwift/Extensions/JSONEncoderExt.swift @@ -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 + } +}