How to convert an object of class NSObject to JSON in Swift?

I have

var  contacts : [ContactsModel] = []

and

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

Now in contacts I have 6 values, for example

enter image description here

Now I want to convert contacts to JSON, how can I?

I tried

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

But this leads to a crash of the application.

My problem is to manually convert to the dictionary one by one a lot of time, it takes more than 5 minutes for 6000 entries, so instead I want to convert the model directly to JSON and send it to the server.

+4
source share
3 answers

A custom object cannot be converted directly to JSON. The NSJSONSerialization class reference says:

, JSON, :

  • - NSArray NSDictionary.

  • NSString, NSNumber, NSArray, NSDictionary NSNull.

  • NSString.

  • NaN .

Dictionary , SwiftyJSON, JSONModel Mantle.

+2

Swift JSON - NSObject NS- . :

https://github.com/peheje/JsonSerializerSwift

. . :

//Arrange your model classes
class Object {
  var id: Int = 182371823
  }
class Animal: Object {
  var weight: Double = 2.5
  var age: Int = 2
  var name: String? = "An animal"
  }
class Cat: Animal {
  var fur: Bool = true
}

let m = Cat()

//Act
let json = JSONSerializer.toJson(m)

, , , NULL, , , .

+2

Source: https://habr.com/ru/post/1619146/


All Articles