2013-05-28 53 views
-1

我已經從json調用中下載了一些json數據Iam試圖將以下json解析爲數組,以便我可以在NSlog中看到問題列表?將json解析爲一個數組以在NSLog中顯示純文本

e.g

NSLog(@"Questions:Air cleaner (Primary), Air Cleaner (Secondary)); 

[ 
{"SurveyAnswerTypeID":4,"Question":"Air cleaner (Primary)"}, 

{"SurveyAnswerTypeID":4,"Question":"Air Cleaner (Secondary)"} 
] 

我試圖把這個放到一個數組,它只會返回一個數組e.g空氣濾清器(小學)

NSString *searchQuery = [NSString stringWithFormat:@"http://www.ddproam.co.za/Central/Survey/GetSurveyQuestions?surveyId=%@",self.surveyQuestionIDParsed]; 

searchQuery = [searchQuery stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:searchQuery]]; 

NSURL *url = [[NSURL alloc] initWithString:searchQuery]; 

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; 

// to receive the returend value 
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]; 

NSLog(@"strResult: %@",strResult); 

NSLog(@"searchQuery: %@", searchQuery); 

NSError *error; 

self.json2 = [NSJSONSerialization JSONObjectWithData:dataURL 
              options:kNilOptions 
               error:&error]; 

NSDictionary* defineJsonData = [self.json2 lastObject]; 

NSNumber* surveyID = [defineJsonData objectForKey:@"SurveyID"]; 
NSLog(@"UserID: %@", surveyID); 

NSArray* userQuestions = [defineJsonData objectForKey:@"Question"]; 

NSLog(@"Question for Survey: %@", userQuestions); 

回答

1

您的代碼運行正常。兩種意見:

  1. 當您設置defineJsonData你只抓住了最後一個項目。如果你想通過所有這些迭代,你會做這樣的事情:

    for (NSDictionary *defineJsonData in self.json2) 
    { 
        NSNumber* surveyID = [defineJsonData objectForKey:@"SurveyID"]; 
        NSLog(@"SurveyID: %@", surveyID); 
    
        NSArray* userQuestions = [defineJsonData objectForKey:@"Question"]; //for actual json response 
        NSLog(@"Question for Survey: %@", userQuestions); //3 
    } 
    
  2. 順便說一句,創造顯然不需要NSURLNSURLRequest對象的數據已經加載你的兩條線而你不使用這兩個對象。

+0

非常感謝,讓我更好地理解。這很有意義。謝謝。 @搶 –