gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:43:53 32 4
gpt4 key购买 nike

基于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仅理解字典和数组。您必须在自定义类中提供一个将其属性转换为Dictionary的方法,如下所示:

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

关于ios - iOS/Objective-C:将自定义对象的NSArray转换为JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51224184/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com