isair / JSONHelper

✌ Convert anything into anything in one operation; JSON data into class instances, hex strings into UIColor/NSColor, y/n strings to booleans, arrays and dictionaries of these; anything you can make sense of!
Other
784 stars 63 forks source link

Request: Object serialization to JSON string #24

Open OmarKan opened 9 years ago

OmarKan commented 9 years ago

It would be awesome to implement serialization of swift objects to JSON strings :+1:
Is it possible to do so using this excellent library ? Thank you...

┆Issue is synchronized with this Asana task

isair commented 9 years ago

Serialization of any kind is sadly not supported, and this library is deserialization focused right now. Not making any promises but it may be supported in the future after I turn this into a dynamic library and give it a proper rewrite (while maintaining backwards compatibility, of course).

lancy commented 9 years ago

I'm building something to do the serialization, and it's design to do it in a similar way like deserialization. it's not finished yet. but if someone need this asap, try my code below:

class IdName: NSObject, Deserializable, Serializable {
    var id: Int?
    var name: String?

    func toJSONDictionary() -> JSONDictionary {
        var data = JSONDictionary()
        id --> data["id"]
        name --> data["name"]
        return data
    }

    required init(data: JSONDictionary) {
        super.init()
        id <-- data["id"]
        name <-- data["name"]
    }
}
protocol Serializable {
    func toJSONDictionary() -> JSONDictionary
}

infix operator --> { associativity right precedence 150 }

func --> <T>(property: T?, inout value: AnyObject?) -> AnyObject? {
    if let int = property as? Int {
        value = int
    } else if let string = property as? String {
        value = string
    } else if let float = property as? Float {
        value = float
    } else if let double = property as? Double {
        value = double
    } else if let instance = property as? Serializable {
        value = instance.toJSONDictionary()
    }
    return value
}

func --> (properties: [Any]?, inout value: AnyObject?) -> AnyObject? {
    if let intArray = properties as? [Int] {
        value = intArray
    } else if let stringArray = properties as? [String] {
        value = stringArray
    } else if let floatArray = properties as? [Float] {
        value = floatArray
    } else if let doubleArray = properties as? [Double] {
        value = doubleArray
    } else if let instances = properties as? [Serializable] {
        value = instances.map { ins in ins.toJSONDictionary() }
    }
    return value
}

@isair I'd like to contribute this project. any suggestion?

isair commented 9 years ago

@lancy I was planning something similar. The difference is I am thinking of wrapping all conversions in a function like convertAndAssign(a, to: b) and then use that in defining <-- and --> operators.