从json字符串中提取值

时间:2014-03-02 15:10:22

标签: objective-c json api

我正在尝试学习如何在Objective-C中使用API​​。我正在使用此处的数据:https://btc-e.com/api/2/ltc_usd/ticker我只想要'last'值。我试过像这样提取值:

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中提取值的唯一方法,但我似乎无法找到如何做到这一点。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

NSString *jsonStr = [json objectForKey:keys[0]];
^^^^^^^^^^^^^^^^^
// nope, it's a NSDictionary...

......它已经被解析了!

如果你NSLog,你会看到它的内容。以下是在last解析JSON后访问NSJSONSerialization字段的方法:

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSNumber *last = json[@"ticker"][@"last"];

就是这样。


作为旁注

NSData * data = [NSData dataWithContentsOfURL:url];

非常糟糕,因为它是同步的!考虑使用异步方法(核 - 可能最好 - 选项是使用AFNetworking)。这是一个完整的AFNetworking示例:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"https://btc-e.com/api/2/ltc_usd/ticker" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
    NSNumber *last = JSON[@"ticker"][@"last"];
    NSLog(@"last value: %@", last);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];