2013-04-18 85 views
0

我想用SBJson解析一些json數據來顯示當前溫度。本教程中的示例代碼完美:Tutorial: Fetch and parse JSONSBJson顯示爲null

當我將代碼更改爲我的json提要時,我得到一個空值。我對JSON很陌生,但是遵循了我發現的每一個教程和文檔。 JSON的來源,我用:JSON Source

我的代碼以sbjson:

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
self.responseData = nil; 

NSArray* currentw = [(NSDictionary*)[responseString JSONValue] objectForKey:@"current_weather"]; 

//choose a random loan 
NSDictionary* weathernow = [currentw objectAtIndex:0]; 

//fetch the data 
NSNumber* tempc = [weathernow objectForKey:@"temp_C"]; 
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"]; 


NSLog(@"%@ %@", tempc, weatherCode); 

,當然,我已經實現了其他sbjson代碼。

+0

如果這是一個新項目,您應該考慮使用Apple的官方['NSJSONSerialization'](https:// developer。apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html)。 – rid

+0

瞭解如何閱讀JSON - 大概需要5分鐘:http://www.json.org/ –

+0

與您的問題矛盾* SBJson不顯示任何*。它只是用於解析JSon。 – viral

回答

2

您發佈的JSON數據中沒有current_weather密鑰。其結構是:

{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } } 

這裏有一個直觀表示:

JSON visual representation

因此,去temp_C,你需要先獲得頂級data屬性:

NSDictionary* json = (NSDictionary*)[responseString JSONValue]; 
NSDictionary* data = [json objectForKey:@"data"]; 

然後,由此獲得current_location財產:

NSArray* current_condition = [data objectForKey:@"current_condition"]; 

最後,從current_location陣列,讓你感興趣的元素:

NSDictionary* weathernow = [current_condition objectAtIndex:0]; 

還要注意的是temp_CweatherCode是字符串,而不是數字。把它們轉化而不是向數字:

NSNumber* tempc = [weathernow objectForKey:@"temp_C"]; 
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"]; 

你可以使用類似:

int tempc = [[weathernow objectForKey:@"temp_C"] intValue]; 
int weatherCode = [[weathernow objectForKey:@"weatherCode"] intValue]; 

(或floatValue/doubleValue如果該值不應該是一個int,而是float或一double

你會再使用%d(或%ffloat/double)作爲格式字符串:

NSLog(@"%d %d", tempc, weatherCode); 
+0

謝謝,我得到它的工作!您提供的代碼中存在一個小問題:NSDictioanry * current_condition = [data objectForKey:@「current_condition」]; 需要成爲: NSArray * currentConditions = [data objectForKey:@「current_condition」]; –

+0

@AndrewHo,你說得對,謝謝。更新。 – rid

0

使用NSJSONSerialization而不是JSONValue

NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding]; 
      NSDictionary* jsonDict = [NSJSONSerialization 
             JSONObjectWithData:data 
             options:kNilOptions 
             error:&error]; 
NSLog(@"jsonDict:%@",jsonDict); 

在您的鏈接中,沒有current_weather密鑰。

NSString* tempc = [[[[jsonDict objectForKey:@"data"] objectForKey:@"current_condition"] objectAtIndex:0] objectForKey:@"temp_C"]; 
0

提供的鏈接返回json沒有current_weather參數。只有current_condition參數,請查看。