我在
JSON文件中找到我想要的数据时遇到了一些麻烦.这是我的控制台输出的缩短版本:
{ AUD = { 15m = "125.15547"; 24h = "124.74"; buy = "121.0177"; last = "125.15547"; sell = "123.44883"; symbol = "$"; }; BRL = { 15m = "120.34"; 24h = "120.34"; buy = "120.34"; last = "120.34"; sell = "120.34"; symbol = "R$"; }; CAD = { 15m = "129.08612"; 24h = "131.07"; buy = "128.66227"; last = "129.08612"; sell = "129.08612"; symbol = "$"; }; }
我正在尝试使用内置的JSON解析库来解析文件.这是我的viewDidLoad方法中的解析器:
_tickerArray = [NSMutableArray array]; NSURL *tickerDataURL = [NSURL URLWithString:@"https://blockchain.info/ticker"]; NSData *jsonData = [NSData dataWithContentsOfURL:tickerDataURL]; NSError *error = nil; NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; NSLog(@"%@",dataDictionary); NSArray *ar = [NSArray arrayWithObject:dataDictionary]; for (NSString *key in [dataDictionary allKeys]) { for (NSDictionary *dict in ar) { TickerData *t; t.currency = [dict objectForKey:key]; t.symbol = [dict objectForKey:@"symbol"]; t.last = [dict objectForKey:@"last"]; [_tickerArray addObject:t]; } }
我想将货币代码(如AUD或BRL)与货币字典中包含的一些其他数据一起存储到t.currency中,但现在我的应用程序崩溃了.
错误代码:
NSInvalidArgumentException',reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil
似乎没有任何对象被添加到_tickerArray中
帮帮我?
编辑:使用填充其他字段的正确数据显示键:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; NSLog(@"%@",dataDictionary); for (NSString *key in [dataDictionary allKeys]) { NSDictionary *dic=[dataDictionary objectForKey:key]; TickerData *t=[[TickerData alloc] init]; t.currency = key;//EDITED t.symbol = [dic objectForKey:@"symbol"]; t.last = [dic objectForKey:@"last"]; [_tickerArray addObject:t]; }
@R_403_323@
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; NSLog(@"%@",dataDictionary); //NSArray *ar = [NSArray arrayWithObject:dataDictionary];//REMOVED for (NSString *key in [dataDictionary allKeys]) { NSDictionary *dic=[dataDictionary objectForKey:key];//ADDED for (NSString *dickey in [dic allKeys]) { //MODIFIED NSDictionary *dict=[dic objectForKey:dicKey];//ADDED TickerData *t=[[TickerData alloc] init];//ALLOC INIT ? t.currency = key;//EDITED t.symbol = [dict objectForKey:@"symbol"]; t.last = [dict objectForKey:@"last"]; [_tickerArray addObject:t]; } }
您的数据不包含任何数组,其所有词典,请尝试上面的代码,请参阅注释..
希望它有效..
编辑:
是的,您也初始化了对象,如上面其他答案所示.