问题
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:
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];
来源:https://stackoverflow.com/questions/51224184/ios-objective-c-convert-nsarray-of-custom-objects-to-json