我在获取 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 or 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];
}