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.

6
  • 1
    converting 6000 dictionaries a 6 entries should not take 5 min. you are doing something wrong there. But without your code we won't be able to help you there. Commented Dec 9, 2015 at 8:34
  • @vikingosegundo ill check and update you Commented Dec 9, 2015 at 9:02
  • Let us check. Post the code. Commented Dec 9, 2015 at 9:10
  • Yes u are right @vikingosegundo. it takes only 2 seconds in for loop for 6000 records. I finished my question by sending in 500 of batch size to server. Commented Dec 10, 2015 at 4:49
  • did u send one by one before? Resulting in 6000 network requests? Requests are slow, even on a fast network. You should always try to minimize the amount. Commented Dec 10, 2015 at 11:41

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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.
It sounds like there is something wrong with your code. Converting 6000 objects should only take milliseconds, not minutes.
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.
SwiftyJSON is the worst library. I used it for NSObject and it showed SwiftyJSON.SwiftyJSONError.unsupportedType. Downvoted for mentioning wrong library ;)
@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
|
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.

2 Comments

I am not getting proper data for my NSObject class as it breaks on many places
Parth could you create an issue on Github with the class you are trying to serialize?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.