将字典持有日期转换为 Swift 中的 JSON

Converting a Dictionary holding dates to JSON in Swift

我有一个相当大且复杂的 NSManagedObject,我在我的应用程序中对其进行操作并作为 JSON 发送回服务器。我的计划是在我的应用程序中做我需要做的事情,将对象转换为字典,然后在调用 NSJSONSerialization.dataWithJSONObject 之后发送它(我也尝试过使用 SwiftyJSON,我认为这是做或多或少相同的事情)。在我需要包括一些日期之前,这一切都很好。

基本上我看到的所有文档都说序列化适用于特定的对象类型列表,其中不包括 NSDate。可悲的是,我需要一些日期。我应该注意,我正在使用一个字典的字典,这些字典的日期可能分散在树的上下,所以如果我递归 运行 通过将它们全部转换为字符串,我将不得不做一个整体大量复制到 NSMutable 词典。当然有更简单的方法吗?我对 Swift 和 iOS 开发有点陌生,我不禁觉得我要么做错了什么,要么有一个内置的解决方案来解决这个问题只是失踪了。我不可能是第一个想要发回 JSON 日期的人。任何帮助将不胜感激。

谢谢, 亚历克斯

Apple NSJSONSerialization Class Reference 说;

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.

我认为您应该将日期转换为字符串并将它们添加到您的词典中。但它说;其他规则可能适用。调用 isValidJSONObject: 尝试用你的 NSDate 对象创建一个字典并调用 isValidJSONObject 如果它 returns true 它应该工作。