0

我有点坚持使用 UIpicker。这是我的 JSON 数据:

{
    "contact_id": [
        "455",
        "464"
    ],
    "contact_name": [
        "Administrator",
        "Main contact"
    ]
}

我将数据存储到一个 NSdictionary 中,然后在转换为对象后,我创建了一个 NSarray 来存储联系人。在我的 Viewcontroller.m 我有: UIPicker with object and keys using JSON

// Creating an URL object
NSURL *url = [NSURL URLWithString:@"http://web.com/json.php"];    
//Creating the data object that will hold the content of the URL
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
contactlist = [result objectForKey:@"contact_name"];

我可以使用联系人列表将联系人值显示到下拉列表中。这是我的其他代表

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

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
        return [contactlist count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
         return [contactlist objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component{
contactTextField.text = (NSString *)[contactlist objectAtIndex:row];
}

我想向所选联系人的相应 ID 发送 JSON 发布请求。

例如,如果您选择 contact_name Administrator,我想获取它的contact_id455 我创建了一个方法

- (IBAction)SendMessage:(id)sender ;

在将 JSON 数据发送到我的服务器端脚本之前创建它,这是我需要传递 id 而不是联系人姓名的地方

// NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"603",  @"contact",nil];

我创建了这个数组试图解决这个问题,但无法让它工作。

contactid = [result objectForKey:@"contact_id"];
4

2 回答 2

2

好的,我想我知道明白你的问题。可能有几种解决方案。但我会通过一个刚刚进入我的人。

如果 id 的数组与名称的顺序相同,只需创建一个新数组

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

NSArray* ids = (NSArray*)[result objectForKey:@"contact_id"];

然后在方法中:

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component{}

执行以下操作获取对应的id:

NSString *idSentToServer = (NSString *)[ids objectAtIndex:row];
于 2013-02-20T01:12:48.703 回答
0

我确实理解在您的案例中定义 JSON 的方式可能是可能的。您的 JSON 数据是否应该返回 JSON 对象数组?

如下:

[{"contact_id":"455","contact_name":"Administrator"},{"contact_id":"464","contact_name":"Main contact"}]
于 2013-02-20T01:33:35.687 回答