Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftyJSON: Converting Objects to JSON

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.

like image 267
user1107173 Avatar asked Nov 28 '15 05:11

user1107173


1 Answers

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
        ]
    }
}
like image 91
Pavel Smejkal Avatar answered Oct 12 '22 07:10

Pavel Smejkal