2013-04-18 4 views
0

SBJson과 함께 일부 json 데이터를 분석하여 현재 온도를 표시하려고합니다. 이 자습서의 예제 코드는 완벽하게 작동합니다. Tutorial: Fetch and parse JSONSBJson이 null을 표시합니다.

코드를 json 피드로 변경하면 null이됩니다. 나는 JSON에 처음 익숙하지만, 내가 찾은 모든 튜토리얼과 문서를 따랐다. 내가 사용하는 JSON 소스 : sbjson와 JSON Source

내 코드 :

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 : // developers.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", ... } ], ... } } 

은 시각적 표현입니다 : temp_C에 도착, 따라서

JSON visual representation

먼저 최고 레벨 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)

그런 다음 float/double) 등을 위해 %d (또는 %f을 사용 형식 문자열 :

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

제공된 링크는 current_weather 매개 변수없이 json을 반환합니다. current_condition 매개 변수 만 있습니다. 이것을 검토하십시오.

관련 문제