0

I have a list of custom objects. Every property in a custom objects is of type String. I have a problem to convert that list of objects to JSON string so I can send it to web service:

var bytes = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.allZeros, error: nil)
    var jsonObj = NSJSONSerialization.JSONObjectWithData(bytes!, options: nil, error: nil) as! [Dictionary<String, String>]

data is a list of objects. This should be simple thing to do and I list two days on it.

3
  • data should be an NSData object, so then you can create a String object from data Commented Apr 16, 2015 at 11:06
  • First try to convert your list of custom objects into a list dictionary. And then try to create the json. Hope it will work. Commented Apr 16, 2015 at 11:10
  • You need to write code to create either a top level array or dictionary that contains only JSON compatible objects. Then NSJSONSerialization.JSONObjectWithData. Commented Apr 16, 2015 at 11:12

1 Answer 1

3

As stated in Apple doc

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.

So you can't use custom objects with String properties. Use a Dictionary representation of the object instead.

UPDATE: I can give you an example in Objective-C:

Given a simple Person object:

@interface Person : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *surname;
@property (copy, nonatomic) NSString *age;
@end

You can create a method for getting the dictionary like this:

-(NSDictionary *) dictionaryRepresentation {
    return @{@"name":self.name,
             @"surname":self.surname,
             @"age":self.age};
}

It can be placed in a category or directly inside the class.

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

1 Comment

Can you show me how I can convert object to dictionary?

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.