【问题标题】:Extract value from json string从json字符串中提取值
【发布时间】: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


【解决方案1】:
NSString *jsonStr = [json objectForKey:keys[0]];
^^^^^^^^^^^^^^^^^
// nope, it's a NSDictionary...

...已经被解析了!

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

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);
}];

【讨论】:

  • 哇,我不敢相信我把它弄得太复杂了! AFNetworking 部分是做什么的?
  • 这是一个网络框架。它基本上将 Objective-C 网络 API 包装成一个更好的基于块的 API。
  • @user2397282 w.r.t.你的具体情况它使调用异步,因此它不会阻塞你正在执行它的线程(如果它是你要阻塞UI的主线程,直到请求被执行!)
  • 请注意,last 的返回值将是 NSNumber,而不是 NSString。
  • @GabrielePetronella 我尝试过使用你的异步方法,但是运行时它给了我一个错误,基本上是说链接中的数据格式错误:text/html,而不是json?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多