IOS/Objective-C:将自定义对象的 NSArray 转换为 JSON

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

基于 the accepted answer to this answer,我正在尝试通过 JSON 将一组自定义对象发送到服务器。

但是,以下序列化对象的代码崩溃了。我认为是因为 NSJSONSerialization 只能接受 NSDictionary,不能接受自定义对象。

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];

任何人都可以建议将自定义对象数组转换为 JSON 的方法吗?

就像你说的,NSJSONSerialization只懂字典和数组。您必须在自定义 class 中提供一种方法,将其属性转换为字典,如下所示:

@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];