How to convert NSObject class object into JSON in Swift?

Shrikant K picture Shrikant K · Dec 9, 2015 · Viewed 12.5k times · Source

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.

Answer

Peheje picture Peheje · Jan 18, 2016

If you just want a simple Swift object to JSON static function without any inheritance or dependencies to NSObject or NS-types directly. Check out:

https://github.com/peheje/JsonSerializerSwift

Full disclaimer. I made it. Simple use:

//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)

Currently supports standard types, optional standard types, arrays, arrays of nullables standard types, array of custom classes, inheritance, composition of custom objects.