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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user6631314
  • 1,751
  • 1
  • 13
  • 44
  • Possible duplicate of [serialize objective-c custom object to JSON for OSX?](https://stackoverflow.com/questions/12808793/serialize-objective-c-custom-object-to-json-for-osx) and [Serialize and Deserialize Objective-C objects into JSON](https://stackoverflow.com/questions/7172001/serialize-and-deserialize-objective-c-objects-into-json) – rmaddy Jul 07 '18 at 15:38

1 Answers1

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];
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • 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]? – user6631314 Jul 08 '18 at 16:17