Accessing JSON data inside an NSDictionary generat

2019-06-06 13:25发布

Having some trouble accessing the JSON data in the following URL ( http://jamesstenson.com/portraits/?json=1 ), basically I want to access the "full" "url"'s underneath "attachments". My code at the moment is as follows:

NSError *e = nil;
NSData *jsonFeed = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://jamesstenson.com/portraits/?json=1"]]; 
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:jsonFeed options:NSJSONReadingMutableContainers error: &e];

if (!jsonData) {
    NSLog(@"Error parsing JSON: %@", e);
} else {

    for(NSDictionary *item in [jsonData objectForKey:@"page"]) {
        for(NSDictionary *attachment in [item objectForKey:@"images"]) {
            NSLog(@"%@", attachment);
        }
    }
}

This keeps throwing up an error:

2011-12-21 10:13:39.362 JSON[3463:f803] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6a7b500

2011-12-21 10:13:39.363 JSON[3463:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6a7b500'

I am aware I am accessing the items wrongly, but cannot figure out how to achieve this. I've tried several solutions such as http://blogs.captechconsulting.com/blog/nathan-jones/getting-started-json-ios5 - but no luck. I am complete newbie to iOS development and have a little knowledge of JSON. Thanks for everyones help in advance.

1条回答
可以哭但决不认输i
2楼-- · 2019-06-06 14:09

The problem is in you for loop

for(NSDictionary *item in [jsonData objectForKey:@"page"]) 

You won't get NSDictionary in item, it will return you key of Dictionary, which would be NSString

Check this link for each loop in objective c for accessing NSMutable dictionary to know how to traverse through NSDictionay

Below is the modified code for your requirement, might help you

if (!jsonData) {
        NSLog(@"Error parsing JSON: %@", e); } else {
        NSArray *attachments = [[jsonData objectForKey:@"page"] objectForKey:@"attachments"];
        for(NSDictionary *object in attachments) {
              NSLog(@"%@", [object objectForKey:@"images"]);
              NSLog(@"%@", [[[object objectForKey:@"images"] objectForKey:@"full"] objectForKey:@"url"]);
        } 
}
查看更多
登录 后发表回答