JSON goes into a dictionary nicely, but objectForKey errors

Go To StackoverFlow.com


I have a RESTful API serving JSON. I'm calling it like this:

- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: 
        [self performSelectorOnMainThread:@selector(fetchedData:) 
                               withObject:data waitUntilDone:YES];

Then I have my fetchedData method:

- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:responseData //1

    //NSArray *projects = [json objectForKey:@"name"]; //2

    NSLog(@"name: %@", json); //3

If I uncomment //NSArray line I get -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6d81720

With it commented out, my dictionary logs:

        "created_at" = "2012-04-04T01:46:51Z";
        description = "First Project Created";
        id = 1;
        name = "Test 1";
        "updated_at" = "2012-04-04T01:46:51Z";
        "created_at" = "2012-04-04T01:47:23Z";
        description = "Second Project Created";
        id = 2;
        name = "Test 2";
        "updated_at" = "2012-04-04T01:47:23Z";
2012-04-04 02:42
by Mike Z
I have read in other similar problems that where I have NSArray, I should have NSDictionary. Making this change gives me the exact same error (different instance 0x####### obviously) - Mike Z 2012-04-04 02:46
And your question is... - James Sumners 2012-04-04 02:47


You have an array of dictionaries, not a dictionary of arrays. Instead of objectForKey, use objectAtIndex and assign to a dictionary. Do this:

NSDictionary *projects = [[json objectAtIndex:0] objectForKey:@"name"];
2012-04-04 02:52
by Adam Shiemke
Thanks! I had to change NSDictionary* json to an NSArray and then used your above code and it worked perfectly. Thank you - Mike Z 2012-04-04 03:06