user817851 user817851 - 23 days ago 8
JSON Question

Converting a Dictionary holding dates to JSON in Swift

I have a fairly large and complex

NSManagedObject
that I'm manipulating within my application and sending back to a server as JSON. My plan was to do what I need to do in my application, convert the object to a Dictionary, and then send it along after calling
NSJSONSerialization.dataWithJSONObject
(I've also tried using
SwiftyJSON
, which I think is doing more or less the same thing). This was all working fine until I needed to include some dates.

Basically all of the documentation I've seen says that serialization works just fine with a certain list of object types, which does not include
NSDate
. Sadly, I need some dates. I should note that I am working with a dictionary of dictionaries that may have dates scattered all up and down the tree, so if I recursively run through to convert them all to strings I'm going to have to do a whole lot of copying to
NSMutable
dictionaries. Surely there's an easier way? I'm a bit new to Swift and iOS development and I can't help feeling like I'm either doing something wrong or that there is a built-in solution to this problem that I'm just missing. I can't be the first person who wants to send back a date as JSON. Any help would be much appreciated.

Thanks,
Alex

Answer

Apple NSJSONSerialization Class Reference says;

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

An object that may be converted to JSON must have the following properties:

The top level object is an NSArray or NSDictionary.

All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

All dictionary keys are instances of NSString.

Numbers are not NaN or infinity.

Other rules may apply. Calling isValidJSONObject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.

I think you should convert your dates to String and add them to your Dictionary. But it says; Other rules may apply. Calling isValidJSONObject: Just try to create a dictionary with your NSDate object and call the isValidJSONObject if it returns true it should be work.