微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Swift中将NSObject类对象转换为JSON?

我有

var  contacts : [ContactsModel] = []

class ContactsModel: NSObject
{
   var contactEmail : String?
   var contactName : String?
   var contactNumber : String?
   var recordId : Int32?
   var modifiedDate : String?
}

现在在联系人中,我有6个值

enter image description here

现在我想将联系人转换成JSON我怎么样?

我试过了

var jsonData: NSData?
        do
        {
            jsonData = try NSJSONSerialization.dataWithJSONObject(contacts,options:NSJSONWritingOptions.PrettyPrinted)
        } catch
        {
            jsonData = nil
        }
  let jsonDataLength = "\(jsonData!.length)"

但它崩溃了应用程序.

我的问题是手动转换为字典逐个非常耗时,6000条记录需要超过5分钟,所以我想直接将模型转换为JSON并发送到服务器.

解决方法

您的自定义对象无法直接转换为JSON. NSJSONSerialization Class Reference说:

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.

您可以手动将对象转换为字典,或使用某些库,如SwiftyJSON,JSONModelMantle.

编辑:目前,使用swift 4.0,您可以使用Codable协议轻松地将对象转换为JSON.这是一个原生解决方案,不需要第三方库.请参阅Apple的Using JSON with Custom Types文档.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐