【发布时间】:2014-04-03 11:17:59
【问题描述】:
我正在尝试学习如何将 API 与 Objective-C 一起使用。我正在使用这里的数据:https://btc-e.com/api/2/ltc_usd/ticker,我只想要“最后一个”值。我尝试过像这样提取值:
NSURL * url=[NSURL URLWithString:@"https://btc-e.com/api/2/ltc_usd/ticker"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSArray *keys = [json allKeys];
NSString *jsonStr = [json objectForKey:keys[0]];
NSArray *c1 = [jsonStr componentsSeparatedByString:@"last = \""];
NSArray *c2 = [[c1 objectAtIndex:1] componentsSeparatedByString:@"\";"];
NSString *result = [c2 objectAtIndex:0];
NSLog(@"%@", result);
但是,这给了我以下错误:
2014-03-02 15:03:24.915 Litecoin Ticker[5727:303] -[__NSDictionaryM componentsSeparatedByString:]: unrecognized selector sent to instance 0x608000240690
2014-03-02 15:03:24.915 Litecoin Ticker[5727:303] -[__NSDictionaryM componentsSeparatedByString:]: unrecognized selector sent to instance 0x608000240690
我不完全确定这是从 API 中提取值的唯一方法,但我似乎不知道该怎么做。有人可以帮忙吗?
【问题讨论】:
-
访问 json.org 并学习 JSON 语法。这需要 5-10 分钟,知道它会让一切更容易理解。
-
并且没有必要使用
componentsSeparatedByString。只需使用objectForKey(或使用[]的新表单)引用NSDictionarys。NSNumber* last = json[@"ticker"][@"last"]; -
(并且,尤其是在从网络上获取数据时,始终检查来自 NSJSONSerialization 的值,如果为零,则至少 NSLog 的
error值。)
标签: objective-c json api