0

我想用 JSON 数据(已经过验证)填充主从应用程序,并且收到错误“未捕获的异常 __NSCFDictionary objectAtIndexedSubscript”。非常感谢。

JSON 文件:

{
    "Name": [
    "Entry 1 (Comment1) (Comment1b)",
    "Entry 2 (Comment2) ",
    "Entry 3 (Comment3) ",
    "Entry 4 (Comment4) (Comment4b)"
     ],
"URLs": [
    "http://www.myurl.com/%20(Comment1)%20(Comment1b)",
    "http://www.myurl.com/%20(Comment2)%20(Comment2b)",
    "http://www.myurl.com/%20(Comment3)%20(Comment3b)",
    "http://www.myurl.com/%20(Comment4)%20(Comment4b)"
    ]
}

这就是我加载 JSON 文件的方式:

@interface MasterViewController () {
    NSArray *_objects;
}
@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:@"http://myurl.com/Data.json"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    _objects = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return _objects.count;
}

这就是我解析它的方式:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSLog(@"_objects contains: %@", _objects);

    // # This following line creates the error:
    NSDictionary *object = _objects [indexPath.row];
    NSLog(@"object contains: %@", object);
    cell.textLabel.text = [object objectForKey: @"Name"];
    cell.detailTextLabel.text = [object objectForKey: @"URLs"];

    return cell;
}
4

1 回答 1

1

您以错误的方式访问了 JSON 字典。顶级对象是字典,但您将它们视为数组并尝试通过 indexPath.row 加载。

像这样的东西应该可以代替:

cell.textLabel.text = _objects[@"Name"][indexPath.row];
cell.detailTextLabel.text = _objects[@"URLs"][indexPath.row];

拆开来看,是这样的:

NSArray *nameArray = _objects[@"Name"];
NSArray *urlArray = _objects[@"URLs"];
cell.textLabel.text = nameArray[indexPath.row];
cell.detailTextLabel.text = urlArray[indexPath.row];
于 2013-11-08T23:52:41.947 回答