将json解析为数组以在NSLog中显示纯文本

时间:2013-05-28 12:36:57

标签: objective-c arrays json

我已经从json调用中下载了一些json数据,现在我试图将以下json解析成一个数组,以便我可以在我的NSlog中看到问题列表?

例如

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

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

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

我试图把它放到一个数组中,它只会返回一个数组,例如Air cleaner(Primary)

  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 个答案:

答案 0 :(得分: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对象的两行,因为数据已经加载并且您不使用这两个对象。 / p>