michael blaize
michael blaize

Reputation: 11

Cannot access NSDictionary

I created a JSON using a PHP script. I am reading the JSON and can see that the data has been correctly read. However, when it comes to access the objects I get unrecognized selector sent to instance...

Cannot seem to find why that is after too many hours. Any help would be great!

My code looks like that:

NSDictionary *json = [[NSDictionary alloc] init];
json = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];

NSLog(@"raw json = %@,%@",json,error);  

NSMutableArray *name = [[NSMutableArray alloc] init];

[name addObjectsFromArray: [json objectForKey:@"name"]];

The code crashes when reaching the last line above.

The output like this:

raw json = (
        {
        category = vacancies;
        link = "http://blablabla.com";
        name = "name 111111";
        tagline = "tagline 111111";
    },
        {
        category = vacancies;
        link = "http://blobloblo.com";
        name = "name 222222222";
        tagline = "tagline 222222222";
    }
),(null)
2012-06-23 21:46:57.539 Wind expert[4302:15203] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0xdcfb970

HELP !!!

Upvotes: 0

Views: 174

Answers (2)

mattjgalloway
mattjgalloway

Reputation: 34912

json is an array from what you've shown, not a dictionary. I can tell this because of the parentheses surrounding the whole of the log output for json. Inside the array are dictionaries, which I can tell by the fact that they are surrounded by braces.

So, it looks like you want something like this:

NSError *error = nil;
NSArray *json = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];

NSLog(@"raw json = %@,%@",json,error);  

NSMutableArray *name = [[NSMutableArray alloc] init];
for (NSDictionary *obj in json) {
    [name addObject:[obj objectForKey:@"name"]];
}

As an aside you will notice I have removed the unnecessary initialisation of json to an object before overwriting in the next line with JSONObjectWithData:options:error:. In an ARC world it wouldn't be a leak but it's still completely unnecessary to allocate an object just to get rid of it again a moment later. Also I added in the NSError *error = nil; line since that was not there and was obviously necessary to compile.

Upvotes: 2

Chris Trahey
Chris Trahey

Reputation: 18290

The problem appears to be that the root level of your JSON is an array, not a dictionary (note the parenthesis instead of curly brace as the first character in the logged output). Arrays do not have objectForKey selector. Perhaps you intend to take objectAtIndex:0 first, or else iterate over all the the items?

As an aside, the first line of your code makes a completely wasted initialization of an NSDictionary. It is simply overwritten and deallocated on the very next line.

Upvotes: 1

Related Questions