我似乎在解析嵌套JSON結果時遇到了一個小問題。如果JSON沒有嵌套,以下代碼完美工作。對於如何進行嘗試(通過其他人的例子)失敗,我是一個小問題困擾。從JSON檢索嵌套對象 - 目標C
因此,爲了測試這個我用下面的API從https://developer.worldweatheronline.com/page/explorer-free
我只是想獲得我的當前溫度(temp_c)。
以下是調用該服務的代碼。請注意,我有一個將填充數據的NSObject,但當然我似乎無法進入該階段。而且它始終是一個NSMutableArray。再次,我不認爲這是問題,但提供了背景。
-(void)retrieveLocalWeatherService {
NSURL *url = [NSURL URLWithString:getLocalWeather];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//set up array and json call
weatherArray = [[NSMutableArray alloc]init];
//Loop through the JSON array
for (int i = 0; i< jsonArray.count; i++)
{
//create our object
NSString *nTemp = [[jsonArray objectAtIndex:i]objectForKey:@"temp_C"];
NSString *nPressure = [[jsonArray objectAtIndex:i]objectForKey:@"pressure"];
NSString *nHumidity = [[jsonArray objectAtIndex:i]objectForKey:@"humidity"];
//Add the object to our animal array
[weatherArray addObject:[[LocalWeather alloc]initWithtemp:(nTemp) andpressure:nPressure andhumidity:nHumidity]];
}
這是JSON響應。
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"FeelsLikeC": "31",
"FeelsLikeF": "88",
"humidity": "70",
"observation_time": "05:15 AM",
"precipMM": "0.0",
"pressure": "1011",
"temp_C": "28",
"temp_F": "82",
"visibility": "10",
"weatherCode": "116",
"weatherDesc": [
{
"value": "Partly Cloudy"
}
],
"weatherIconUrl": [
{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"
}
],
"winddir16Point": "N",
"winddirDegree": "10",
"windspeedKmph": "41",
"windspeedMiles": "26"
}
],
"request": [
{
"query": "Brisbane, Australia",
"type": "City"
}
],
我切斷了JSON服務,因爲它走了幾英里,所以我錯了哪裏?我相信它在「for-loop」的某個位置,但我不確定它在哪裏。我知道它的主要節點是「數據」,然後子節點是「current_condition」。我應該挖掘JSON結果嗎?如果最好的辦法是什麼。
順便說一句,我收到服務器的響應與整個JSON result..clearly解析問題我的一部分。
在此先感謝! 請親切我是個新手。
謝謝!我不知道鑽取JSON路徑的正確語法。那是我剛剛脫落的地方。我還發現JSON對象區分大小寫。爲了返回值,data.current_condition需要小寫。真棒幫助謝謝! – Jeremy 2014-11-21 23:48:44