如何在iOS中的表视图中检索json数据

时间:2016-04-29 05:04:29

标签: ios objective-c arrays json uitableview

我不知道如何从这个JSON数据中检索特定数据并在tableview中插入。

{
"error": "ok",
"data": [{
    "facebook_id": "1068644546541665",
    "user_id": "95590e92-6c74-44d1-9e5c-5a10c6341ba3",
    "name": "Sunil",
    "trackingallowed": 1,
    "trackingpermission": 1
}, {
    "facebook_id": "10311905002886663",
    "user_id": "95ab5fc0-9c6d-4e3e-9cb2-bfa4d53e640f",
    "name": "Saravanan",
    "trackingallowed": 1,
    "trackingpermission": 1
}, {
    "facebook_id": "998936463528828",
    "user_id": "cd6e3c89-bc2d-45a9-8436-9603e1b4724b",
    "name": "Suresh",
    "trackingallowed": 1,
    "trackingpermission": 1
}]

}

通过List数组获取值。

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
 [friendsconnection_data appendData:data];
    NSError *localerror;
    NSDictionary *parsedobject =[NSJSONSerialization   JSONObjectWithData:data options:0 error:&localerror];
    NSLog(@"parsedobject1 %@",parsedobject);
    ListArray = [parsedobject valueForKey:@"data"];

    NSLog(@"rrresults1 %lu",(unsigned long)ListArray.count);
    NSLog(@"results1 %@",ListArray );   
}  

我正在获得EXC_BAD_ACCESS。我需要知道如何从JSON获取特定数据。例如我只想获得facebookidname

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self FriendsData];
    static NSString *TableIdentifier =@"tableitem";
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:TableIdentifier];
    if(cell == nil)
    {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
    }
    cell.textLabel.text = [[ListArray objectAtIndex:indexPath.row]objectForKey:@"name"];
    tableView.rowHeight = 300;

    return cell;
}

1 个答案:

答案 0 :(得分:-2)

使用此代码。我认为它可以帮助你

NSError *json_parse_error;
NSDictionary *responseDictionary=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&json_parse_error];
NSArray *user_info_array=[responseDictionary valueForKey:@"data"];

在您的表格视图委托

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TableIdentifier=@"tableitem";;
    cell=[tableView dequeueReusableCellWithIdentifier:TableIdentifier];

    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:TableIdentifier];
    }

    cell.textLabel.text = [[user_info_array objectAtIndex:indexPath.row] objectForKey:@"name"];

    cell.detailTextLabel.text = [[user_info_array objectAtIndex:indexPath.row] objectForKey:@"facebook_id"];

    return cell;
}

//设置表格视图单元格的高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300.0;
}