我在获取想要在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方法中的解析器 :
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 or BRL)t.currency与货币词典中包含的其他一些数据一起存储,但是现在我的应用崩溃了。错误代码:
AUD or BRL
t.currency
NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil
似乎没有任何对象添加到 _tickerArray
_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]; }
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]; } }
您的数据不包含任何数组,而是所有字典,请尝试上面的代码以及注释。
希望它能..
编辑:
是的,您也已初始化对象,如上面其他答案中所建议。