Skip to content

Instantly share code, notes, and snippets.

@scottrhoyt
Last active March 27, 2021 00:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save scottrhoyt/be266a72e7ee593276a98724cfde3eff to your computer and use it in GitHub Desktop.
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])
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