Search code examples
jsonswiftnsobjectnsjsonserialization

How to convert NSObject class object into 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'm having 6 values like

enter image description here

Now i want to convert contacts into 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 it crashes the app.

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.


Solution

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

    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.

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

    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.