Last active
March 27, 2021 00:19
-
-
Save scottrhoyt/be266a72e7ee593276a98724cfde3eff to your computer and use it in GitHub Desktop.
A Swift 4 extension for JSONEncoder and JSONDecoder to enable serialization to/deserialization from JSON Objects (e.g. [String: Any])
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
import Foundation | |
extension JSONEncoder { | |
func encodeJSONObject<T: Encodable>(_ value: T, options opt: JSONSerialization.ReadingOptions = []) throws -> Any { | |
let data = try encode(value) | |
return try JSONSerialization.jsonObject(with: data, options: opt) | |
} | |
} | |
extension JSONDecoder { | |
func decode<T: Decodable>(_ type: T.Type, withJSONObject object: Any, options opt: JSONSerialization.WritingOptions = []) throws -> T { | |
let data = try JSONSerialization.data(withJSONObject: object, options: opt) | |
return try decode(T.self, from: data) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment