JSONHelper icon indicating copy to clipboard operation
JSONHelper copied to clipboard

Request: Object serialization to JSON string

Open OmarKan opened this issue 10 years ago • 3 comments

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

OmarKan avatar Feb 02 '15 20:02 OmarKan

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).

isair avatar Feb 16 '15 20:02 isair

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?

lancy avatar Apr 28 '15 06:04 lancy

@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.

isair avatar May 02 '15 20:05 isair