Skip to content

Instantly share code, notes, and snippets.

@yoxisem544
Forked from krzyzanowskim/JSONCodable.swift
Created January 8, 2020 05:19
Show Gist options
  • Save yoxisem544/1dd90774ed537ba4cdcc7c03aa095785 to your computer and use it in GitHub Desktop.
Save yoxisem544/1dd90774ed537ba4cdcc7c03aa095785 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