Skip to content

Instantly share code, notes, and snippets.

@joshuajhomann
Last active June 19, 2019 19:28
Show Gist options
  • Save joshuajhomann/67c2072de0586cbff0d7d6cf463ced47 to your computer and use it in GitHub Desktop.
Save joshuajhomann/67c2072de0586cbff0d7d6cf463ced47 to your computer and use it in GitHub Desktop.
JSONIntitalizable
protocol JSONIntitalizable {
init?( json: [String: Any])
}
extension JSONIntitalizable where Self: Decodable{
init?( json: [String: Any]) {
self = (try? JSONSerialization.data(withJSONObject: json, options: []))
.flatMap{ try? JSONDecoder().decode(Self.self, from: $0) }!
}
}
protocol JSONRepresentable {
init?(json: [String: Any])
func json() -> [String: Any]?
}
extension JSONRepresentable where Self: Codable {
init?(json: [String:Any]) {
guard let value = (try? JSONSerialization.data(withJSONObject: json, options: []))
.flatMap ({ try? JSONDecoder().decode(Self.self, from: $0) }) else {
return nil
}
self = value
}
func json() -> [String:Any]? {
return (try? JSONEncoder().encode(self))
.flatMap { try? JSONSerialization.jsonObject(with: $0, options: []) } as? [String: Any]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment