Skip to content

Instantly share code, notes, and snippets.

@MaximShoustin
Forked from turowicz/swift-json-class.md
Last active August 29, 2015 14:06
Show Gist options
  • Save MaximShoustin/4386a71526d252cb6f04 to your computer and use it in GitHub Desktop.
Save MaximShoustin/4386a71526d252cb6f04 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
typealias JSON = AnyObject
typealias JSONObject = Dictionary<String, JSON>
typealias JSONArray = Array<JSON>
class Serializable : NSObject{
func toDictionary() -> NSDictionary {
var aClass : AnyClass? = self.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafeMutablePointer<Ivar> = class_copyIvarList(aClass, &propertiesCount)
var propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
for var i = 0; i < Int(propertiesCount); i++ {
var property = propertiesInAClass[i]
var propName:String = NSString(CString: ivar_getName(propertiesInAClass[Int(i)]), encoding: NSUTF8StringEncoding)
println(propName)
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 Dictionary<String,AnyObject>
{
var subDictionary : NSMutableDictionary = NSMutableDictionary()
for (key, object) in propValue as Dictionary<String,AnyObject> {
var subArray = Array<NSDictionary>()
for item in (object as Array<Serializable>) {
subArray.append(item.toDictionary())
}
subDictionary.setValue(subArray, forKey: key)
}
propertiesDictionary.setValue(subDictionary, forKey: propName)
}
else if propValue is NSData {
propertiesDictionary.setValue(propValue.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength), 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)
}
}//for
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)
}
func toJsonString(data:NSData) -> NSString! {
return NSString(data: data, encoding: NSUTF8StringEncoding)
}
func getJSONDictinoryFromNSData(myEncodedObject:NSData) -> JSONObject{
var output:JSONObject = JSONObject()
var error: NSError?
let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(myEncodedObject, options: NSJSONReadingOptions(0), error: &error)
println("Error: \(error)")
if anyObj is JSONObject {
if let temp: AnyObject = anyObj {
let fetchedObj: AnyObject! = temp["map"] as AnyObject!
if fetchedObj is JSONObject{
println("im JSON Dictinory")
output = fetchedObj as JSONObject
}
}
}
return output
}// func
func getJSONArrayFromNSData(myEncodedObject:NSData) -> JSONArray{
var output:JSONArray = []
var error: NSError?
let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(myEncodedObject, options: NSJSONReadingOptions(0), error: &error)
println("Error: \(error)")
if anyObj is JSONObject {
if let temp: AnyObject = anyObj {
let fetchedArray: AnyObject! = temp["list"] as AnyObject!
println(fetchedArray.count)
if fetchedArray is JSONArray{
println("im JSON Array")
output = fetchedArray as JSONArray
}
}
}
return output
}// func
override init() { }
}
class JsonWrapper : Serializable{
var map:Dictionary<String,AnyObject> = Dictionary<String,AnyObject>()
}
class UserClass : Serializable{
var name:String?
override init(){
super.init()
}
}
var dict:Dictionary<String, Array<UserClass>> = Dictionary<String, Array<UserClass>>()
var user1:UserClass = UserClass()
var user2:UserClass = UserClass()
var user3:UserClass = UserClass()
var user4:UserClass = UserClass()
var user5:UserClass = UserClass()
user1.name = "u1"
user2.name = "u2"
user3.name = "u3"
user4.name = "u4"
user5.name = "u5"
var someArray1:Array<UserClass> = [user1, user2]
var someArray2:Array<UserClass> = [user3]
var someArray3:Array<UserClass> = [user4, user5]
dict["available_slots_asap"] = someArray1
dict["available_slots_future"] = someArray2
dict["available_slots_soon"] = someArray3
if (dict as AnyObject!) is Dictionary<String,AnyObject>{
println("yes")
}
var jw:JsonWrapper = JsonWrapper()
jw.map = dict
var data:NSData = jw.toJson()
var str:String = jw.toJsonString(data)
var obj:JSONObject = jw.getJSONDictinoryFromNSData(data)
}
}
@MaximShoustin
Copy link
Author

I added 1st version, will continue to fix in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment