【问题标题】:Wunderground API json lookup on iPhoneiPhone上的Wunderground API json查找
【发布时间】:2012-01-01 19:27:15
【问题描述】:

以前从未接触过 json。我正在尝试访问Melbourne 的 Wunderground 天气 API 中的一些变量。例如,假设我想访问 "wind_dir":"East" 变量。到目前为止,这是我的代码:

NSString *urlString = 
    [NSString stringWithFormat:
     @"http://api.wunderground.com/api/key/geolookup/conditions/forecast/q/-33.957550,151.230850.json"];

    NSLog(@"URL = %@", urlString);

    SBJsonParser *parser = [[SBJsonParser alloc] init];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

    NSArray *weatherInfo = [parser objectWithString:json_string error:nil];

    for (NSDictionary *weatherString in weatherInfo)
    {

        NSLog(@"some weather info = %@", [[[weatherString objectForKey:@"response"] objectForKey:@"current_observation"] objectForKey:@"wind_dir"]);

    }

我的代码到达 for 循环并因以下错误而崩溃:-[NSCFString objectForKey:]: unrecognized selector sent to instance.

我不能 100% 确定导致崩溃的原因,以及我的“wind_dir”变量路径是否正确,尽管它们很可能是同一个问题。

提前感谢您的帮助。

【问题讨论】:

  • 如果我是你,我会从链接中删除你的私钥。
  • @Tibidabo 好点,谢谢。

标签: iphone objective-c json weather-api


【解决方案1】:

“response”属性或“current_observation”属性是字符串而不是字典。

你得到的错误是你试图在一个字符串上调用“objectForKey”。

查看API的结果后,似乎没有得到数组。

你应该这样做:

    NSDictionary *weatherInfo = [parser objectWithString:json_string error:nil];

    NSLog(@"some weather info = %@", [[weatherInfo objectForKey:@"current_observation"] objectForKey:@"wind_dir"]);

而不是你的 for 语句。

【讨论】:

  • 工作就像一个魅力。非常感谢!
猜你喜欢
  • 2017-12-08
  • 2015-01-04
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 2017-02-06
相关资源
最近更新 更多