-1

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

例如

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

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

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

我试图将它放入一个数组中,它只会返回一个数组,例如空气净化器(初级)

  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); 
4

1 回答 1

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. 顺便说一句,显然不需要创建NSURLandNSURLRequest对象的两行,因为数据已经加载并且您不使用这两个对象。

于 2013-05-28T12:51:51.320 回答