I want to fill a master-detail app with JSON data (which is already validated), and am getting error "uncaught exception __NSCFDictionary objectAtIndexedSubscript". Thanks a lot.

The JSON file:

{
    "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)"
    ]
}

This is how I load the JSON file:

@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;
}

This is how I am parsing it:

- (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;
}
有帮助吗?

解决方案

You've got you access of the JSON dictionary around the wrong way. The top level objects are dictionaries, but you are treating them as arrays and trying to load by the indexPath.row.

Something like this should work instead:

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

Broken out, it looks like this:

NSArray *nameArray = _objects[@"Name"];
NSArray *urlArray = _objects[@"URLs"];
cell.textLabel.text = nameArray[indexPath.row];
cell.detailTextLabel.text = urlArray[indexPath.row];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top