2013-05-16 131 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