我有 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个值
现在我想将联系人转换成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文档.