我有许多自定义类,它们是从NSObject继承的,试图将其写入JSON文件。我的顶级类称为Survey,是一个单例,其属性之一是addressArray,其中包含另一个名为Address的类的实例。
Survey的addressArray中可以有任意数量的地址,而我正在尝试将所有数据写入JSON文件。我的代码如下:
//In both Survey.m and Address.m, I have a method like this:
- (NSDictionary *)surveyDictionaryRepresentation
{
NSMutableDictionary *dictionary = [NSMutableDictionary new];
dictionary[@"name"] = [self name] ? : [NSNull null];
dictionary[@"emailAddress"] = [self emailAddress] ? : [NSNull null];
dictionary[@"addressArray"] = [self addressArray] ? : [NSNull null];
dictionary[@"storage"] = [NSNumber numberWithInteger:[self storage]] ? : [NSNull null];
dictionary[@"extraStops"] = [NSNumber numberWithBool:[self extraStops]] ? : [NSNull null];
return [NSDictionary dictionaryWithDictionary:dictionary];
}
然后,在视图控制器中,在ViewDidLoad方法中具有以下内容。
NSArray *surveys = @[[[Survey sharedInstance] surveyDictionaryRepresentation]];
NSMutableArray *addresses = [[NSMutableArray alloc]init];
for (Address *address in [[Survey sharedInstance]addressArray]){
//What the hell was I thinking?
[addresses addObject:[addressaddressDictionaryRepresentation]];
}
NSDictionary *dictionary = @{@"Survey": surveys, @"Address":addresses};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
现在,我收到以下错误:
由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“ JSON写入(地址)中的类型无效”
我明白为什么会有问题了。由于包含Survey实例的addressArray位于Survey中,因此将Address数据添加到为Survey创建的JSON对象中似乎存在问题。我不确定如何解决这个问题。使用断点单步执行程序后,我发现尝试执行该行后发生崩溃:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
对于它的价值,在循环遍历并在其内容上运行addressesDictionaryRepresentation方法后,我NSLog记录了addresss数组,并且记录完美,完美显示了所有属性和所有值。我只是无法将其放入JSON文档中。有什么建议么?非常感谢您的帮助。
编辑:AddressArray的日志的前几行:
2015-02-18 11:21:29.122 [70958:920733] (
{
aCCOI = "-1";
aCfloorNumber = "<null>";
activity = 0;
addressType = "-1";
allowedToReserveDock = "-1";
编辑2:Survey.m中唯一的其他代码是建立单例的代码:
+(实例类型)sharedInstance {
静态调查* _instance;
静态dispatch_once_t OnceToken;
dispatch_once(&onceToken,^ {
_instance = [[Survey alloc] init];
});
返回_instance;
}
编辑3:
如果([self addressArray]){
NSMutableArray *地址= [[NSMutableArray alloc] init];
用于([*调查[[Survey sharedInstance] addressArray]中的地址){
[地址addObject:[地址addressDictionaryRepresentation]];
}
dictionary [@“ addressArray”] = [self addressArray];
}其他{
dictionary [@“ addressArray”] = [NSNull null];
}
最佳答案
[self addressArray]应该返回一个JSON数组,而不是带有Address对象的数组。就像您对@“ Address”字段所做的一样:NSMutableArray *addresses = [[NSMutableArray alloc]init];for (Address *address in [[Survey sharedInstance]addressArray]){ [addresses addObject:[addressaddressDictionaryRepresentation]];
}
返回该NSMutableArray地址,以便将其设置为@“ addressArray”的值。那你应该没事的。