就像你说的,
NSJSONSerialization
只理解字典和数组。您必须在自定义类中提供一个将其属性转换为字典的方法,如下所示:
@interface Offers
@property NSString* title;
-(NSDictionary*) toJSON;
@end
@implementation Offers
-(NSDictionary*) toJSON {
return @{
@"title": self.title
};
}
@end
然后您可以将代码更改为
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];