我想用 JSON 数据(已经验证)填充主从应用程序,并收到错误"对象索引下标未捕获__NSCFDictionary异常"。多谢。
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;
}
你以错误的方式访问了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];