iOS/Objective-C:将自定义对象的NSArray转换为JSON [英] IOS/Objective-C: Convert NSArray of Custom Objects to JSON

查看:633
本文介绍了iOS/Objective-C:将自定义对象的NSArray转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于对此答案的可接受答案,我是尝试通过JSON将自定义对象数组发送到服务器.

Based on the accepted answer to this answer, I am trying to send an array of custom objects via JSON to a server.

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

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

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

Can anyone suggest way to convert an array of custom objects to JSON?

推荐答案

就像您说的那样,NSJSONSerialization仅理解字典和数组.您必须在自定义类中提供一个将其属性转换为Dictionary的方法,如下所示:

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

这篇关于iOS/Objective-C:将自定义对象的NSArray转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆