Как получить данные из JSON, используя ключ в iPhone

Эй, я новичок в iPhone и я пытался разобрать ниже JSON для отображения различных типов Survey используя мой код ниже. У меня есть две таблицы, в первой таблице я хочу отобразить все "Surveys_title" текстовое значение, и как только пользователь нажмет на любую строку заголовка опроса, он должен отобразить question а также question ID в моем втором столе. Как у меня есть два вопроса для "Survey1" и три вопроса "Survey2", Используя мой код, я могу отобразить все survey titles в моей первой таблице, но я получаю проблему, как хранить массив объектов для всех типов опросов по отдельности. здесь я создал один пользовательский класс "Survey", Спасибо за любую помощь, которую вы можете оказать мне.

JSON:

{
    "Surveys": [
        {
            "Surveys_title": "Survey1",
            "Questions": [
                {
                    "event_sq_qns_id": 1,
                    "questions": "What is your primary job title/focus?"
                },
                {
                    "event_sq_qns_id": 2,
                    "questions": "Effectiveness of the speakers?"
                }
            ]
        },
        {
            "Surveys_title": "Survey2",
            "Questions": [
                {
                    "event_sq_qns_id": 3,
                    "questions": "What is this?"
                },
                {
                    "event_sq_qns_id": 4,
                    "questions": "Who are you?"
                },
                {
                    "event_sq_qns_id": 5,
                    "questions": "what is your name?"
                }
            ]
        },
        {
            "Surveys_title": "Survey3",
            "Questions": [
                {
                    "event_sq_qns_id": 6,
                    "questions": "What is your primary job?"
                },
                {
                    "event_sq_qns_id": 7,
                    "questions": "Effectiveness of the speakers?"
                }
            ]
        }
    ]
}

вот мой код:

#import <Foundation/Foundation.h>

@interface Surveys : NSObject

@property (nonatomic, retain) NSString *surveys_question_id;
@property (nonatomic, retain) NSString *questions;

@end


- (void) fetchingSurveyQuestionsFromServer
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *results;
        @try {

            NSString *filePath = [[NSBundle mainBundle] pathForResource:@"survey" ofType:@"json"];
            NSData *responseData = [NSData dataWithContentsOfFile:filePath];

            //parse the json data
            NSError *error;
            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                                 options:kNilOptions
                                                                   error:&error];

            results= [json objectForKey:@"Surveys"];
        }
        @catch (NSException *exception) {
            NSLog(@"Exception in %s %@",__FUNCTION__,exception);

        }
        dispatch_async (dispatch_get_main_queue (),
                        ^{
                            arraySurveys = [[NSMutableArray alloc] init];
                            arraySurveys_type = [[NSMutableArray alloc] init];
                            NSString *surveys_title_name;

                            for (NSDictionary *dict in results) {
                                NSDictionary *questionDict = dict[@"Questions"];
                                surveys_title_name = dict[@"Surveys_title"];

                                NSLog(@"Questions dictionary = %@", questionDict);
                                NSLog(@"Survey type is = %@", surveys_title_name);

                                for (NSDictionary *dict1 in questionDict) {
                                    Surveys *surveys = [[Surveys alloc] init];

                                    surveys.surveys_question_id = [dict1 objectForKey:@"event_sq_qns_id"];
                                    surveys.questions = [dict1 objectForKey:@"survey_questions"];

                                    [arraySurveys addObject:surveys];
                                }
                                [arraySurveys_type addObject:surveys_title_name];
                            }

                            [MBProgressHUD hideHUDForView:self.view animated:YES];
                            [tblSurveys reloadData];
                        });
    });
}

Используя приведенный выше код, все вопросы добавляются непосредственно в arraySurveys. Пожалуйста, помогите мне, как я могу дифференцироваться согласно названию Обзоров.

Благодарю.

1 ответ

Используйте как это....

 SBJSON *json = [[SBJSON alloc] init];
 NSMutableDictionary *jsonObject = [json objectWithString:response ];
 NSMutableArray *Surveys=[jsonObject valueForKey:@"Surveys"];
 NSMutableArray * Surveys_title =[[NSMutableArray alloc]init];
 NSMutableArray * Questions =[[NSMutableArray alloc]init];    

    for (NSDictionary *dictnory in Surveys) {
        [Surveys_title addObject:[dictnory objectForKey:@"Surveys_title"]];
        [Questions addObject:[dictnory objectForKey:@"Questions"]];

    }
Другие вопросы по тегам