ios - 带有对象和键的 UIPicker 使用 JSON

标签 ios objective-c json uipickerview

我有点受困于 UIpicker。这是我的 JSON 数据:

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

我将数据存储到 NSdictionary 中,然后在转换为对象后,我创建了一个 NSarray 来存储联系人。在我的 Viewcontroller.m 中,我有: 带有使用 JSON 的对象和键的 UIPicker

// 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];
}

我想发送一个 JSON post 请求到所选联系人的相应 ID。

例如,如果您选择 contact_name Administrator,我想获取其 contact_id 455 我创建了一个方法

- (IBAction)SendMessage:(id)sender ;

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

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

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

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

最佳答案

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

如果 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];

关于ios - 带有对象和键的 UIPicker 使用 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970316/

相关文章:

iOS 相当于 Android registerActivityLifecycleCallbacks

ios - UITextField InputAccessoryView 崩溃应用程序

iOS - 从 plist 中提取数据不起作用

ios - NSDateFormatter 问题,而来自字符串的 NSDate 仅包含时间

ios - 刷新一个 UIPageViewController

python - 将目录树表示为 JSON

ios - 信号 sigabrt 委托(delegate) -> AppDelegate.swift

iphone - 多个注释数组,每个数组的引脚颜色不同?

javascript - 将 javascript 对象编号设置为 x 和 y 值

java - 如何在android中的单个对象中解析嵌套的json数组