Skip to content

Instantly share code, notes, and snippets.

@rkeniger
Forked from turowicz/swift-json-class.md
Last active August 29, 2015 14:05
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 rkeniger/c22f116049e9b02ef621 to your computer and use it in GitHub Desktop.
Save rkeniger/c22f116049e9b02ef621 to your computer and use it in GitHub Desktop.
/*
Converts A class to a dictionary, used for serializing dictionaries to JSON
Supported objects:
- Serializable derived classes
- Arrays of Serializable
- NSData
- String, Numeric, and all other NSJSONSerialization supported objects
*/
import Foundation
class Serializable : NSObject{
func toDictionary() -> NSDictionary {
var aClass : AnyClass? = self.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount)
var propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
for var i = 0; i < Int(propertiesCount); i++ {
var property = propertiesInAClass[i]
var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding)
var propType = property_getAttributes(property)
var propValue : AnyObject! = self.valueForKey(propName);
if propValue is Serializable {
propertiesDictionary.setValue((propValue as Serializable).toDictionary(), forKey: propName)
} else if propValue is Array<Serializable> {
var subArray = Array<NSDictionary>()
for item in (propValue as Array<Serializable>) {
subArray.append(item.toDictionary())
}
propertiesDictionary.setValue(subArray, forKey: propName)
} else if propValue is NSData {
propertiesDictionary.setValue((propValue as NSData).base64EncodedStringWithOptions(nil), forKey: propName)
} else if propValue is Bool {
propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName)
} else if propValue is NSDate {
var date = propValue as NSDate
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "Z"
var dateString = NSString(format: "/Date(%.0f000%@)/", date.timeIntervalSince1970, dateFormatter.stringFromDate(date))
propertiesDictionary.setValue(dateString, forKey: propName)
} else {
propertiesDictionary.setValue(propValue, forKey: propName)
}
}
return propertiesDictionary
}
func toJson() -> NSData! {
var dictionary = self.toDictionary()
var err: NSError?
return NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error: &err)
}
func toJsonString() -> NSString! {
return NSString(data: self.toJson(), encoding: NSUTF8StringEncoding)
}
init() { }
}
import XCTest
class Person:Serializable{
var Name : String
var Surname : String
var Animals : Array<Animal>
init(Name:String, Surname:String) {
self.Name = Name
self.Surname = Surname
self.Animals = Array<Animal>()
}
}
class Animal:Serializable {
var Nickname : String
var Kind : String
init(Nickname : String, Kind : String) {
self.Nickname = Nickname
self.Kind = Kind
}
}
class SerializationTests: XCTestCase {
func test_serialization_works() {
var john = Person(Name: "John", Surname: "Doe")
john.Animals.append(Animal(Nickname: "Fluffy", Kind: "Dog"))
john.Animals.append(Animal(Nickname: "Purry", Kind: "Cat"))
println(john.toJson()) //will give binary data to include in HTTP Body
println(john.toJsonString()) //will give the exact string in JSON
//{"Surname":"Doe","Name":"John","Animals":[{"Kind":"Dog","Nickname":"Fluffy"},{"Kind":"Cat","Nickname":"Purry"}]}
var expected = "{\"Surname\":\"Doe\",\"Name\":\"John\",\"Animals\":[{\"Kind\":\"Dog\",\"Nickname\":\"Fluffy\"},{\"Kind\":\"Cat\",\"Nickname\":\"Purry\"}]}";
XCTAssertEqual(john.toJsonString(), expected,"")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment