Search code examples
iosobjective-cjsonafnetworking-2

AFNetworking with JSON giving objectForKey


I am trying to access my JSON and I get that part done. But when I want access a particular item in the JSON, I get the

    '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance

Here is the following code:

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCredential:credentials];
    [operation setResponseSerializer:[AFJSONResponseSerializer serializer]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success");
        jsonOutputData = [NSMutableArray arrayWithObject:responseObject];
        NSLog(@"%@", [[jsonOutputData objectAtIndex:0] objectForKey:@"comments"]);

        NSLog(@"The Array: %@",jsonOutputData);

        //[self.newsFeed reloadData];

    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Failure: %@", error);
    }];

    [operation start];

And my JSON is pretty simple:

   [  
    {  
  "id":"2043",
  "user_id":"5",
  "created_time":"2015-03-24 22:32:58",
  "post_type":"3",
  "post_link":"google.ca",
  "message":null,
  "photo":{  
     "height":"266",
     "width":"720",
     "link":"google.ca",
     "thumbnail":"jpg",
     "source":"jpg"
  },
  "likes":"88029",
  "shares":"170",
  "comments":"850",
   }
 ]

Any kind of help would be appreciated! If there are any questions, please ask and I will try my best to give you the necessary information!

Thanks

Here is the JSON output

    (
       (
            {
        comments = 868;
        "created_time" = "2015-03-24 22:32:58";
        id = 2043;
        likes = 88309;
        message = "<null>";
        photo =             {
            height = 266;
            link = "google.ca";
            thumbnail = "jpg";
            width = 720;
        };
        "post_link" = "google.ca";
        "post_type" = 3;
        shares = 175;
        "user_id" = 5;
    }
  )
)

Solution

  • Because you're using jsonOutputData = [NSMutableArray arrayWithObject:responseObject];. So you're putting your responseObject array into a new array (so you have an array in an array). Then you get the first item out of the array, which is responseObject - an array - and try to access it as a dictionary.

    Just do

    NSLog(@"%@", [[responseObject objectAtIndex:0] objectForKey:@"comments"]);