-
-
Save PaulWoodIII/1f83cd1847c447d45606 to your computer and use it in GitHub Desktop.
Serialize a Swift object to JSON or Dictionary, with selective properties.
This file contains hidden or 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
/** | |
Purpose: | |
Convert (or Serialize) an object to a JSON String or Dictionary. | |
Usage: | |
Use 'Serialize.toJSON' on instances of classes that: | |
- Inherit from NSObject | |
- Implement 'Serializable' protocol | |
- Implement the property 'jsonProperties' and return an array of strings with names of all the properties to be serialized | |
Inspiration/Alternative: | |
https://gist.github.com/anaimi/ad336b44d718430195f8 | |
https://gist.github.com/turowicz/e7746a9c035356f9483d | |
*/ | |
import Foundation | |
@objc protocol Serializable { | |
var jsonProperties:Array<String> { get } | |
func valueForKey(key: String!) -> AnyObject! | |
} | |
struct Serialize { | |
static func toDictionary(obj:Serializable) -> NSDictionary { | |
// make dictionary | |
var dict = Dictionary<String, AnyObject>() | |
// add values | |
for prop in obj.jsonProperties { | |
let val:AnyObject! = obj.valueForKey(prop) | |
if val is String{ | |
dict[prop] = val as! String | |
} | |
else if val is Int{ | |
dict[prop] = val as! Int | |
} | |
else if val is Double{ | |
dict[prop] = val as! Double | |
} | |
else if val is Array<String>{ | |
dict[prop] = val as! Array<String> | |
} | |
else if val is Serializable{ | |
dict[prop] = toJSON(val as! Serializable) | |
} | |
else if val is Array<Serializable>{ | |
var arr = Array<NSDictionary>() | |
for item in (val as! Array<Serializable>) { | |
arr.append(toDictionary(item)) | |
} | |
dict[prop] = arr | |
} | |
} | |
// return dict | |
return dict | |
} | |
static func toJSON(obj:Serializable) -> String? { | |
// get dict | |
let dict = toDictionary(obj) | |
do { | |
// make JSON | |
let data = try NSJSONSerialization.dataWithJSONObject(dict, options:NSJSONWritingOptions(rawValue: 0)) | |
// return result as a String | |
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String | |
} | |
catch _ { | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment