Skip to content

Instantly share code, notes, and snippets.

@SerenadeX
Forked from anaimi/Serializable.swift
Created December 30, 2015 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SerenadeX/89922436a3587d13d8ab to your computer and use it in GitHub Desktop.
Save SerenadeX/89922436a3587d13d8ab to your computer and use it in GitHub Desktop.
Serialize a Swift object to JSON or Dictionary, with selective properties.
/*
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/turowicz/e7746a9c035356f9483d
*/
import Foundation
@objc protocol Serializable {
var jsonProperties:[String] { get }
func valueForKey(key: String!) -> AnyObject!
}
struct Serialize {
static func toDictionary(obj:Serializable) throws -> NSDictionary {
// make dictionary
var dict = [String: AnyObject]()
// add values
for prop in obj.jsonProperties {
let val: AnyObject? = obj.valueForKey(prop)
if let val = val as? String {
dict[prop] = val
}
if let val = val as? Int {
dict[prop] = val
}
if let val = val as? Double {
dict[prop] = val
}
if let val = val as? [String] {
dict[prop] = val
}
if let val = val as? Serializable {
dict[prop] = try toJSON(val)
}
if let val = val as? [Serializable] {
var arr = Array<NSDictionary>()
for item in val {
arr.append(try toDictionary(item))
}
dict[prop] = arr
}
}
// return dict
return dict
}
static func toJSON(obj:Serializable) throws -> String? {
// get dict
let dict = try toDictionary(obj)
let data = try NSJSONSerialization.dataWithJSONObject(dict, options:NSJSONWritingOptions(rawValue: 0))
return String(data: data, encoding: NSUTF8StringEncoding)
// return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment