ios - xcode NSDictionary 错误多数组

标签 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"];

最佳答案

几点观察:

  • 您的 JSON 格式不正确,缺少逗号。它应该是:
    {
        "noticias": [
                     {
                     "titulo":"teste"
                     },
                     {
                     "titulo":"teste 2"
                     }
                     ]
    }
    

    如果你不添加缺少的逗号,你会从你的解析器中得到一个错误。例如,NSJSONSerialization将报告:

    Badly formed array around character 109

  • 要阅读内容,您需要加载 NSData使用 JSON 的内容,然后对其进行解析,例如:
    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);
    }
    


  • 首先,为您的noticias 定义一个属性。在 @interface为您的类(class):
    @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;
    }
    

    关于ios - xcode NSDictionary 错误多数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826988/

    相关文章:

    ios - Firebase Google Sign In (iOS) - 从未调用过 GIDSignInUIDelegate 方法

    iphone - 字典值检索

    ios - 将 JSON 提要转换为 NSDictionary

    ios - UICollectionView 不重新加载数据

    ios - 由于自动布局,滚动后 UITableview 框架发生变化

    ios - 在同一工作区中的 iOS 框架和应用程序项目中使用 Cocoapods

    iphone - 如何使开关转移到另一个 View Controller ?

    xcode - 如何使用 make 文件在 Xcode 中编译项目

    ios - [FIRApp configure] 是否在 iOS 上以 DEBUG 模式发送统计信息?

    ios - 在 Objective-C 中使用 JSON 数据的 NSJSONSerialization 读取 NSDictionary 集的键值