我设置了一个iOS应用程序来下载和解析JSON Feed。它可以很好地获取数据,但我正在努力研究如何读取Feed的某些嵌套JSON数据。
以下是我尝试加载的JSON Feed: http://api.wunderground.com/api/595007cb79ada1b1/conditions/forecast/q/51.5171,0.1062.json
我要加载的JSON Feed部分是:
"forecast":{
"txt_forecast": {
"date":"1:00 AM BST",
"forecastday": [
{
"period":0,
"icon":"chancerain",
"icon_url":"http://icons-ak.wxug.com/i/c/k/chancerain.gif",
"title":"Thursday",
"fcttext":"Clear with a chance of rain in the morning, then mostly cloudy with a chance of rain. High of 59F. Winds from the SSE at 5 to 10 mph. Chance of rain 60%.",
"fcttext_metric":"Clear with a chance of rain in the morning, then mostly cloudy with a chance of rain. High of 15C. Winds from the SSE at 5 to 15 km/h. Chance of rain 60%.",
"pop":"60"
}
你看到有一个叫做“句号”:0和0期间有“icon”,“title”等......
我正在尝试访问该数据,但我不能。
以下是我访问嵌套JSON Feed的某个部分的代码:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *results = [res objectForKey:@"current_observation"];
NSArray *cur = [results valueForKey:@"weather"];
NSArray *windrep = [results valueForKey:@"wind_string"];
NSArray *UVrep = [results valueForKey:@"UV"];
NSArray *othertemprep = [results valueForKey:@"temperature_string"];
NSString *loc = [[results valueForKey:@"display_location"] valueForKey:@"city"];
NSString *countcode = [[results valueForKey:@"display_location"] valueForKey:@"country"];
如何更改以访问我想要的内容?
这是我的另一次尝试:
NSString *test = [[[results valueForKey:@"forecast"] valueForKey:@"period:0"] valueForKey:@"title"];
感谢你的帮助,Dan。
答案 0 :(得分:1)
period
只是forecastday
数组中包含的第一个字典中的一个键,值为0.它不会以任何方式识别字典。
要在forecastday
的第一个元素中获取标题值,您的代码应如下所示:
NSString *title = results[@"forecast"][0][@"title"];
或者,如果您没有使用新的下标语法:
NSString *title =
[[[results objectForKey:@"forecast"] objectAtIndex:0] objectForKey:@"title"];