4

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.

Shrikant K
  • 1,988
  • 2
  • 23
  • 34

3 Answers3

3

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.

Adam
  • 26,549
  • 8
  • 62
  • 79
  • my top level object is an array which contains strings. Is there any way to convert without using any of above SwiftyJSON, JSONModel or Mantle. My issue is with manually converting in to a Dictionary very time consuming it takes more than 5 minutes for 6000 records. – Shrikant K Dec 09 '15 at 06:31
  • 1
    It sounds like there is something wrong with your code. Converting 6000 objects should only take milliseconds, not minutes. – Adam Dec 09 '15 at 11:18
  • Yes u are right. it takes only 2 seconds in for loop for 6000 records. I finished my question by sending in 500 of batch size to server. – Shrikant K Dec 10 '15 at 04:51
  • SwiftyJSON is the worst library. I used it for NSObject and it showed SwiftyJSON.SwiftyJSONError.unsupportedType. Downvoted for mentioning wrong library ;) – Shivam Pokhriyal Sep 17 '18 at 13:52
  • @ShivamPokhriyal SwiftyJSON is a well supported library with 17k stars on Github. It used to be the library of choice for many developers before Apple introduced Codable. That being said, I edited my answer to add some info about Codable – Adam Sep 17 '18 at 14:25
  • @Adam Yes and what are your views about so many issues that are still open in their code and the last activity is about 4 months ago. About the Codable protocol, it won't work if the custom class has NSNumber and NSMutableArray type variables. Please go through this question https://stackoverflow.com/questions/52369799/convert-nsobject-to-json-string I would really appreciate any help regarding this – Shivam Pokhriyal Sep 17 '18 at 16:10
  • My answer was written in 2015, it made sense to use those libraries back then. I'm not using any of them currently. Codable is the way to go in 2018. I have read your question and I would avoid using NSObject, NSNumber and NSMutableArray in Swift if possible. Use swift types and value types instead. If that's not possible, go for `NSJSONSerialization`, as somebody already suggested in comments – Adam Sep 18 '18 at 06:58
3

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.

Peheje
  • 12,542
  • 1
  • 21
  • 30
0

You can use NSJSONSerialization for array when array contains only JSON encodable values (string, number, dictionary, array, nil)

first you need to create the JSON object then you can use it (your code is crashing because contact is not a JSON object!)

you can refere below link

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/doc/uid/TP40010946-CH1-SW9

Suhas Arvind Patil
  • 1,732
  • 1
  • 19
  • 31