我正试图通过他们的JSON API从地下气象中读取数据。我能够读取条件数据,如下所示:
weatherReturn={"current_observation"={UV=1;"露点_c"=2;"露点_f"=35;"露点_string"="35华氏度(2摄氏度)";"display_location"={city=芝加哥;country=US。。。
现在,我正在尝试从预测数据中读取JSON数据,它看起来像这样:
预测={simpleforecast={预测日=({平均湿度=45;avewind={度数=141;dir=SE;kph=14;mph=9;};conditions=清除;日期={ampm=PM;第19天;
而我的代码正在为我试图获取的属性返回null。
由于predict的JSON数据层比条件多,所以我正在尝试一种返回null的新方法。此外,我注意到预测数据的forecast_day后面有一个左paren。
我正在尝试的代码如下:
urlNSString = [NSString stringWithFormat:@"http://api.wunderground.com/api/%@/forecast/q/Chicago.json",
kWeatherAPIKey];
NSURL *url = [NSURL URLWithString:urlNSString];
NSData *weatherCall = [NSData dataWithContentsOfURL:url];
id weatherReturn = [NSJSONSerialization weatherCall options:0 error:&error];
NSMutableDictionary *response = [[[weatherReturn valueForKey:@"forecast"] objectAtIndex:0]mutableCopy];
NSString *parma = [response valueForKey:@"avehumidity"];
NSString *parmb = [response valueForKey:@"pretty"];
NSString *parmc = [response valueForKey:@"ampm"];
NSLog(@"parms are %@%@%@",parma,parmb,parmc);
当我使用此代码运行时,在NSMutableDictionary语句中会出现以下错误:[__NSCFDictionary objectAtIndex:]:无法识别的选择器发送到实例0x9847fa0由于未捕获的异常"NSInvalidArgumentException"而终止应用程序,原因:"-[__NSCFDictionary objectAtIndex:]:无法识别的选择器发送到实例0x9847fa0"
libc++abi.dylib:以NSException 类型的未捕获异常终止
响应不是一个简单的NSDictionary对象。它是一个数组和字典的字典,可能包含其他数组和字典等。
您必须知道响应的结构是什么(例如通过NSLogging)。
尝试:NSLog(@"%@", weatherReturn);
{...}
表示NSDictionary
对象。(...)
表示NSArray
对象
我更改了您的代码,以证明您要查找的参数不是nil
。
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlNSString = [NSString stringWithFormat:@"http://api.wunderground.com/api/%@/forecast/q/Chicago.json",kWeatherAPIKey];
NSURL *url = [NSURL URLWithString:urlNSString];
NSData *weatherCall = [NSData dataWithContentsOfURL:url];
NSError *error;
id weatherReturn = [NSJSONSerialization JSONObjectWithData:weatherCall options:0 error:&error];
NSLog(@"%@", weatherReturn);
id forecast = [weatherReturn valueForKey:@"forecast"];
id simpleforecast = [forecast valueForKey:@"simpleforecast"];
id forecastday = [simpleforecast valueForKey:@"forecastday"];
id firstPartOfDailyForecast = [forecastday firstObject];
id avehumidity = [firstPartOfDailyForecast valueForKey:@"avehumidity"];
id date = [firstPartOfDailyForecast valueForKey:@"date"];
id pretty = [date valueForKey:@"pretty"];
id ampm = [date valueForKey:@"ampm"];
NSLog(@"Ave:%@nPretty:%@nAM/PM:%@", avehumidity, pretty, ampm);
}
重要信息
我并不是一直在weatherReturn上调用valueForKey:
方法,但我对响应结构的了解越来越深。
这就是键为"ampm"
的参数的结构
--NSDictionary (response)
----NSDictionary for key forecast
-------NSDictionary for key simpleforecast
---------NSArray for key forecastday
-----------NSDictionary as first array object
-------------NSDictionary for key date
---------------NSString for key ampm
编辑:
我刚刚发现了这个工具,你可能会觉得它很有用:)
JSON查看器
如何使用:
- 将您的请求(但更改API KEY:))放入浏览器
http://api.wunderground.com/api/YOUR_API_KEY/forecast/q/Chicago.json
- 将API响应复制到工具的"文本"页
- 转到"查看器"页面并分析响应