Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active February 6, 2022 15:38
Show Gist options
  • Save krzyzanowskim/73fbc1ce6f5f72fc945316b8f50a5821 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/73fbc1ce6f5f72fc945316b8f50a5821 to your computer and use it in GitHub Desktop.
// Created by Marcin Krzyzanowski
import Foundation
public protocol JSONEncodable: Encodable { }
public extension JSONEncodable {
func toJSON(using encoder: @autoclosure () -> JSONEncoder = JSONEncoder()) throws -> String {
try String(decoding: encoder().encode(self), as: UTF8.self)
}
}
public protocol JSONDecodable: Decodable { }
public extension JSONDecodable {
static func from(json data: Data, using decoder: @autoclosure () -> JSONDecoder = JSONDecoder()) throws -> Self {
try decoder().decode(Self.self, from: data)
}
static func from(json string: String, using decoder: @autoclosure () -> JSONDecoder = JSONDecoder()) throws -> Self {
try self.from(json: Data(string.utf8), using: decoder())
}
}
public protocol JSONCodable: JSONEncodable & JSONDecodable { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment