我在获取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];
}
答案 0 :(得分:4)
t
为零,你必须分配/初始化它:
TickerData *t = [[TickerData alloc] init];
答案 1 :(得分:3)
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];
}
}
您的数据不包含任何数组,其所有词典,请尝试以上代码,也请查看注释。
希望它有效..
<强>编辑:强>
是的,您也已经初始化了对象,如上面其他答案所示。
答案 2 :(得分:0)
试试吧......
NSURL *url = [NSURL URLWithString:@"https://blockchain.info/ticker"];
NSLog(@"API : %@",url);
NSMutableData *jsonData = [NSMutableData dataWithContentsOfURL:url];
NSString *data = [[NSString alloc] initWithBytes: [jsonData mutableBytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
dictionary = [data JSONValue];
NSDictionary *dict = [dictionary objectForKey:@"AUD"];
NSLog(@"%@",dict);
NSString *last = [dict valueForKey:@"last"];
NSLog(@"%@",last);