IOS/Objective-C: Convert NSArray of Custom Objects to JSON

♀尐吖头ヾ 提交于 2019-12-08 06:06:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!