【发布时间】:2014-06-13 10:24:46
【问题描述】:
嘿,我是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。请帮助我如何根据调查标题进行区分。
谢谢。
【问题讨论】:
-
你想在 tableview 或 uicontrollview 中显示的位置
-
@user3614966.Thanks.. 在表格视图中。
-
然后使用 NSObject 存储数组值
-
是的..我已经使用 NSObject 创建了自定义类“Survey”。这个类有两个属性 1.Question 和 2.question_Id。
-
好的,你在你的 NSObject 的 m 文件中正确地初始化了它们
标签: ios json nsjsonserialization