SwiftyJSON: Converting Objects to JSON

user1107173 picture user1107173 · Nov 28, 2015 · Viewed 11.9k times · Source

I know with SwiftyJSON you can convert the objects from JSON to Swift.

Does SwiftyJSON allows you to go back? i.e. take NSManagedObjects with relationships and converting them it into JSON?

Example Please.

Answer

Pavel Smejkal picture Pavel Smejkal · Nov 28, 2015

You can't do that, that's not what the SwiftyJSON is made for. SwiftyJSON is just using the features of Swift for better parsing of JSON compared to objective-c, it wouldn't bring any value for serialization to JSON.

For your purpose, you have to create dictionary/array from your NSManagedObject object. Then use just Alamofire with JSON serializer like this:

let parameters = event.toJSON() // create Dictionary from NSManagedObject

Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)

The serialization to JSON dictionary – if you have two subclasses of NSManagedObjectEvent and Activity where Event has one-to-many relation to Activity, I would go like this:

extension Event {
    func toJSON() -> Dictionary<String, AnyObject> {
        return [
            "id": self.id,
            "name": self.name,
            "startDate": self.startDate.GMTFormatString,
            "endDate": self.endDate.GMTFormatString,
            "activities": self.activities.map({ $0.toJSON() })   
        ]
    }
}

extension Activity {
    func toJSON() -> Dictionary<String, AnyObject> {
        return [
            "id": self.id,
            "name": self.name
        ]
    }
}