Created
April 9, 2016 15:13
-
-
Save eaigner/d5f85edfa9b3a09c96ab38f2c4720720 to your computer and use it in GitHub Desktop.
Convert Objects to and from JSON
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 | |
protocol JSONConvertible { | |
} | |
extension JSONConvertible { | |
func toJSON() -> [String: AnyObject] { | |
var json = [String: AnyObject]() | |
let mirror = Mirror(reflecting: self) | |
for child in mirror.children { | |
guard let label = child.label, | |
value = child.value as? AnyObject else { | |
continue | |
} | |
json[label] = value | |
} | |
return json | |
} | |
} | |
extension JSONConvertible where Self: NSObject { | |
func setValuesFromJSON(json: [String: AnyObject]) { | |
for (key, value) in json { | |
// The objects fiels must be declared as vars, or this will fail | |
setValue(value, forKey: key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment