0

我有这样的网络服务日期:

{
            "idlife_stage_question" = 43;//..basically this should be key
            "life_stage_idlife_stage" = 1;
            "profile_idprofile" = 0;
            "question_text" = "example";//..this should be object
            sequence = 42;
    }

现在我需要每个 JSON 字典中的“idlife_stage_question”和“question_text”,并在 UIPickerView 中加载“question_text”,然后在 UILabel 中显示选定的行文本。此外,我需要为相应的“question_text”获取“idlife_stage_question”,以便稍后将“idlife_stage_question”发送到服务器。我怎么能用 NSDictionary 做到这一点?

编辑:

我的要求是:

  1. 从 JSON 中获取“idlife_stage_question”和“question_text”。
  2. 在 NSMutableDictionary 中设置“idlife_stage_question”和“question_text”
  3. 使用“question_text”填充 UIPicker
  4. 在标签中显示选定的行文本
  5. 从 NSMutableDictionary 中获取与“question_text”对应的“idlife_stage_question”,将其发送到服务器。
4

2 回答 2

1

Assuming you have self.questionsArray which have all the data from webservice and there is only one component in UIPickerView

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.questionsArray count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
   return self.questionsArray[row][@"question_text"];
}

The method which dismiss the pickerView

- (void)dismissPickerView
{
    //Get the selected Row in picker
    NSInteger selectedQuestionIndex = [self.pickerView selectedRowInComponent:0];
    NSDictionary *question = self.questionsArray[selectedQuestionIndex];

    self.label.text = question[@"question_text"];

    //Use this value to send back to server
    NSInteger questionId = [question[@"idlife_stage_question"] integerValue];

}
于 2013-04-24T08:38:07.477 回答
0

将 json 解析为 nsdictionary

-(void) requestFinished : (ASIHTTPRequest *) request {
        NSArray *myArray = [NSJSONSerialization 
                                              JSONObjectWithData:[request responseData]
                                              options:kNilOptions 
                                              error:&error];
        }

要检查您的数组层次结构:

NSLog(@"%@", myArray);

现在可以将数组的每个元素提取到 NSDictionary 中。当你迭代你的数组时,你得到的每个对象都是一个 NSDictionary。

迭代你的数组

NSEnumerator *myIterator = [myArray objectEnumerator];
    id anObject;

    while( anObject = [myIterator nextObject]){
        NSLog(@"%@", [anObject objectForKey@"question_text"]);
        // get each value of your question_text in a new NSArray and use that array for UIPickerView demostrated in the following link
    }

然后在这里查看如何以编程方式创建 UIPickerView

于 2013-04-24T07:40:00.480 回答