如何在Swift中将NSObject类对象转换为JSON? [英] How to convert NSObject class object into JSON in Swift?

查看:735
本文介绍了如何在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个值,例如

Now in contacts I'm having 6 values like

现在我想将联系人转换为JSON怎么办?

Now i want to convert contacts into JSON how can i ?

我尝试了

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

但是它使应用程序崩溃了.

But it crashes the app.

我的问题是手动将其一一转换为字典,这非常耗时,需要花费5分钟以上的时间才能记录6000条记录,所以我不想直接将模型转换为JSON并发送到服务器.

My issue is with manually converting in to a Dictionary one by one very time consuming it takes more than 5 minutes for 6000 records, So instead of that i want to convert directly model into JSON and send to server.

推荐答案

您的自定义对象无法直接转换为JSON. NSJSONSerialization类参考说:

Your custom object can't be converted to JSON directly. NSJSONSerialization Class Reference says:

可能转换为JSON的对象必须具有以下属性:

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

  • 顶级对象是NSArray或NSDictionary.

  • The top level object is an NSArray or NSDictionary.

所有对象都是NSString,NSNumber,NSArray,NSDictionary或NSNull的实例.

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

所有字典键都是NSString的实例.

All dictionary keys are instances of NSString.

数字不是NaN或无穷大.

Numbers are not NaN or infinity.

您可以手动将对象转换为Dictionary,也可以使用 SwiftyJSON JSONModel

You might convert your object to a Dictionary manually or use some libraries like SwiftyJSON, JSONModel or Mantle.

编辑:当前,在4.0及更高版本中,您可以使用Codable协议轻松地将对象转换为JSON.这是本机解决方案,不需要第三方库.请参阅将JSON与自定义类型一起使用苹果公司的文件.

Edit: Currently, with swift 4.0+, you can use Codable protocol to easily convert your objects to JSON. It's a native solution, no third party library needed. See Using JSON with Custom Types document from Apple.

这篇关于如何在Swift中将NSObject类对象转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆