1

Based on the accepted answer to this answer, I am trying to send an array of custom objects via JSON to a server.

However, the following code to serialize the objects is crashing. I think it because NSJSONSerialization can only accept an NSDictionary, not a custom object.

NSArray <Offers *> *offers = [self getOffers:self.customer];
//Returns a valid array of offers as far as I can tell.
NSError *error;
//Following line crashes
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:offers
                                                    options:kNilOptions
                                                      error:&error];

Can anyone suggest way to convert an array of custom objects to JSON?

1

1 Answer 1

2

Like you said, NSJSONSerialization only understands Dictionaries and Arrays. You'll have to provide a method in your custom class that converts its properties into a Dictionary, something like this:

@interface Offers 
@property NSString* title;
-(NSDictionary*) toJSON;
@end

@implementation Offers
-(NSDictionary*) toJSON {
    return @{
       @"title": self.title
    };
}
@end

then you can change your code to

NSArray <Offers *> *offers = [self getOffers:self.customer];
NSMutableArray<NSDictionary*> *jsonOffers = [NSMutableArray array];
for (Offers* offer in offers) {
    [jsonOffers addObject:[offer toJSON]];
}
NSError *error;
//Following line crashes
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:jsonOffers
                                                    options:kNilOptions
                                                      error:&error];
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I have discovered that the method toJSON in the custom class (NSManagedObject) is returning empty values. If a property in offers is @property (nonatomic, retain) NSString * title; what would the correct code be to get the title through [offer toJSON]?

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.