Skip to content

Instantly share code, notes, and snippets.

@eaigner
Created April 9, 2016 15:13
Show Gist options
  • Save eaigner/d5f85edfa9b3a09c96ab38f2c4720720 to your computer and use it in GitHub Desktop.
Save eaigner/d5f85edfa9b3a09c96ab38f2c4720720 to your computer and use it in GitHub Desktop.
Convert Objects to and from JSON
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