iPhone 上的 Wunderground API json 查找
之前没接触过json。我正在尝试访问 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:]: 无法识别的选择器发送到实例。
我不能 100% 确定导致崩溃的原因,以及我的“wind_dir”变量的路径是否正确,尽管它们很可能是同一个问题。
预先感谢您的任何帮助。
Never touched json before. I'm trying to access some variables within the Wunderground weather API for Melbourne. For example, let's say I want to access the "wind_dir":"East" variable. This is my code thus far:
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"]);
}
My code reaches the for loop and crashes with this error: -[NSCFString objectForKey:]: unrecognized selector sent to instance.
I'm not 100% sure what's causing the crash, and whether my path to the "wind_dir" variable is correct, though they could well be the same problem.
Thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“response”属性或“current_observation”属性是字符串而不是字典。
您收到的错误是您试图在字符串上调用“objectForKey”。
查看 API 的结果后,您似乎没有获得数组。
你应该做这样的事情:
而不是你的 for 语句。
either the "response" property or the "current_observation" propery is string and not dictionary.
the error you are getting is that you are trying to call "objectForKey" on a string.
after looking at the result of the API, it seems that you are not getting an array.
You should do something like this:
instead of your for statement.