加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:37:11 所属栏目:百科 来源:网络整理
导读:我有 var contacts : [ContactsModel] = [] 和 class ContactsModel: NSObject{ var contactEmail : String? var contactName : String? var contactNumber : String? var recordId : Int32? var modifiedDate : String?} 现在在联系人中,我有6个值 现在我想
我有

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,JSONModel或Mantle.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读