IOS/Objective-C:将自定义对象的NSArray转换为JSON
基于,我试图通过JSON将一组自定义对象发送到服务器 但是,以下序列化对象的代码正在崩溃。我认为这是因为NSJSONSerialization只能接受NSDictionary,而不能接受自定义对象IOS/Objective-C:将自定义对象的NSArray转换为JSON,ios,objective-c,json,nsjsonserialization,Ios,Objective C,Json,Nsjsonserialization,基于,我试图通过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
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];
NSArray*offers=[self-getOffers:self.customer];
//据我所知,返回有效的报价数组。
n错误*错误;
//跟车碰撞
NSData*JSONData=[NSJSONSerialization dataWithJSONObject:offers
选项:针织品
错误:&错误];
有人能提出将自定义对象数组转换为JSON的方法吗?正如您所说,
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];
NSArray*offers=[self-getOffers:self.customer];
NSMutableArray*jsonOffers=[NSMutableArray];
对于(优惠*优惠中的优惠){
[jsonOffers addObject:[offer to json]];
}
n错误*错误;
//跟车碰撞
NSData*JSONData=[NSJSONSerialization dataWithJSONObject:jsonOffers
选项:针织品
错误:&错误];
Hi的可能重复,我发现自定义类(NSManagedObject)中的toJSON方法返回空值。如果报价中的属性为@property(非原子,保留)NSString*title;通过[offer toJSON]获取标题的正确代码是什么?