xcode NSDictionary错误多阵列

时间:2013-05-30 02:26:29

标签: ios xcode nsdictionary

我是xcode的新手,我需要帮助。

我有这个json:

{
    "noticias": [
        {
             "titulo":"teste"
        }
        {
             "titulo":"teste 2"
        }
    ]
}

我是如何得到结果的?我试过了

NSDictionary *not = [noticias objectAtIndex:indexPath.row];

但我收到错误,因为我有关键的“noticias”


更新:这是根据到目前为止收到的答案尝试的代码。我有这个:

- (void)fetchNoticias
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: @"http://www.site.com/json"]];

        NSError* error;

        noticias = [NSJSONSerialization JSONObjectWithData:data
                                                 options:kNilOptions
                                                   error:&error];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}

然后

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self fetchNoticias];
}

最后我遇到问题

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

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

    NSArray *noticia = [noticias objectForKey:@"noticias"];
    NSDictionary *not = [noticias objectAtIndex:indexPath.row];
    NSString *firstTitle = [not objectForKey:@"titulo"];

    cell.textLabel.text = firstTitle;
    //cell.detailTextLabel.text = subtitulo;

    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

    return cell;
}

问题在线:

NSArray *noticia = [noticias objectForKey:@"noticias"];

3 个答案:

答案 0 :(得分:2)

有几点意见:

  1. 您的JSON格式不正确,缺少逗号。它应该是:

    {
        "noticias": [
                     {
                     "titulo":"teste"
                     },
                     {
                     "titulo":"teste 2"
                     }
                     ]
    }
    

    如果您没有添加丢失的逗号,则解析器会收到错误消息。例如,NSJSONSerialization将报告:

      

    在字符109周围形成错误的数组

  2. 要阅读内容,您需要加载带有JSON内容的NSData,然后解析它,例如:

    NSData *data = [NSData dataWithContentsOfFile:filename]; // or [NSData dataWithContentsOfURL:url];
    NSError *error = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    
    if (error)
        NSLog(@"%@", error);
    else
    {
        NSArray *array = [dictionary objectForKey:@"noticias"];
        NSDictionary *item = [array objectAtIndex:indexPath.row];
        NSString *title = [item objectForKey:@"titulo"];
    
        NSLog(@"%@", firstTitle);
    }
    

    或者,使用新的,更简单的语法:

    NSData *data = [NSData dataWithContentsOfFile:filename]; // or [NSData dataWithContentsOfURL:url];
    NSError *error = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    
    if (error)
        NSLog(@"%@", error);
    else
    {
        NSArray *array = dictionary[@"noticias"];
        NSDictionary *item = array[indexPath.row];
        NSString *title = item[@"titulo"];
    
        NSLog(@"%@", title);
    }
    

  3. 首先,为您班级的noticias中的@interface定义一个属性:

    @property (nonatomic, strong) NSArray *noticias;
    

    然后阅读noticias

    - (void)fetchNoticias
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData* data = [NSData dataWithContentsOfURL:
                            [NSURL URLWithString: @"http://www.site.com/json"]];
    
            NSError* error = nil;
    
            NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:kNilOptions
                                                                      error:&error];
    
            if (error) 
            {
                NSLog(@"%s: error=%@", __FUNCTION__, error);
                return;
            }
    
            self.noticias = [results objectForKey:@"noticias"];
    
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        });
    }
    

    然后

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self fetchNoticias];
    }
    

    ,最后,cellForRowAtIndexPath

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"NoticiasCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
    
        NSDictionary *noticia = [self.noticias objectAtIndex:indexPath.row];
        NSString *firstTitle = [noticia objectForKey:@"titulo"];
    
        cell.textLabel.text = firstTitle;
        //cell.detailTextLabel.text = subtitulo;
    
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    
        return cell;
    }
    

答案 1 :(得分:1)

假设您的jsonData是“响应”

NSError* error;
NSDictionary* ResponseDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSArray* noticias = [ResponseDic objectForKey:@"noticias"];
NSDictionary* not = [noticias objectAtIndex:indexPath.row];

希望这对你有所帮助。

答案 2 :(得分:1)

试试这个

      NSArray *array = [dictionary objectForKey:@"noticias"];
      for(int i=0;i<[array count];i++)
      {
       NSDictionary *item = [array objectAtIndex:i];
      NSString *title = [item objectForKey:@"titulo"];
       NSLog(@"%@",title);
      }

希望对你有所帮助。