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

编程入门 行业动态 更新时间:2024-10-09 06:24:50
本文介绍了如何在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?

本文发布于:2023-11-26 09:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   对象   如何在   NSObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!