SwiftyJSON: Converting Objects to JSON
Asked Answered
Q

1

10

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.

Quinn answered 28/11, 2015 at 5:13 Comment(3)
SwiftyJSON is simple json serializer/deserializer. You need to make sure you have the right data for it. As for relationships, it's your job to have it ready for serialization (i.e. make it a dictionary or some sort). What you are asking is tight integration between Core Data and SwiftyJSON, which there aren't.Horsy
@Quinn how to do you manage to init managed object from JSON ? it's undoable ...Cuttlebone
@Cuttlebone I don't think you can. You have convert it from JSON and manually do the mapping.Quinn
H
5

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
        ]
    }
}
Hamstring answered 28/11, 2015 at 5:40 Comment(9)
Thanks. How would that work for relationships. I.e. If I have an entity called "events" that has a to-Many relationship with "activity" entity. Events will have a Set of activities.Quinn
I would probably implement extension with one serialization method for both classes returning in dictionary. See the updated postHamstring
Also, all I'm having to force unwrap all the attributes. return [ "id": self.id!]. Is this going to cause a crash if one of the values is nil ?Quinn
yes it will. you shouldn't include the values that can be nil or enter some default value insteadHamstring
Hey, this works fine when I do Alamofire.ParameterEncoding.URL.encode. However, when I do Alamofire.ParameterEncoding.JSON.encode I get a crash: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSTaggedDate)'Quinn
I guess you need to save NSDate as number so I would go for date.timeIntervarSince1970 or something like that. Depends on how you need the date on the API endpoint. Somewhere you need to send formatted date according to some standard (Google API uses RFC 3339)Hamstring
I need it to send the date in GMT format as a string, so I left it as that. Can you please make that adjustment to the answer so others can also benefit. Thanks again!Quinn
I'm getting a Generic parameter 'U' could not be inferred exception for .map in Swift3 any suggestions?Webfooted
Did you managed to solve that? Im getting the same error @DaisyR.Wrand

© 2022 - 2024 — McMap. All rights reserved.