2013-05-16 44 views
0

我有一个iOS应用程序设置为下载和解析JSON供稿。它可以很好地获取数据,但我正在努力阅读如何阅读Feed的某些嵌套JSON数据。访问JSON供稿数据

这里是JSON提要我试图加载: http://api.wunderground.com/api/595007cb79ada1b1/conditions/forecast/q/51.5171,0.1062.json

的JSON提要我试图加载的部分是:

"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有”图标“,”标题“等...

嗯,我试图访问该数据,但我不能。

这里是我的访问嵌套的JSON饲料的某部分代码:

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"]; 

感谢您的帮助,丹。

+0

我在您的JSON转储中无法看到“display_location”或“country”。可能想要粘贴它的所有相关部分。 – DrummerB

+0

@DrummerB我现在用完整的代码更新了这篇文章。 – Supertecnoboff

+0

它在哪里失败?在第一行放置一个断点并逐步完成。 – DrummerB

回答

1

period只是forecastday数组中包含的第一个字典中的一个关键字,其值为0.它不以任何方式标识字典。

要获得的forecastday的第一个元素的标题值,你的代码应该是这样的:

NSString *title = results[@"forecast"][0][@"title"]; 

或者,如果你不使用新的下标语法:

NSString *title = 
    [[[results objectForKey:@"forecast"] objectAtIndex:0] objectForKey:@"title"]; 
+0

当我第一次学习如何解析JSON提要时,我发现你的答案真的很难理解。但现在我回头看,它非常简单。谢谢 :) – Supertecnoboff