Search code examples
objective-cxcodejsonkit

JSONKit NSDictionary


Im having problems in JSONkit.h using NSDictionary. Whats the properly way to use it?

Json:

[{"id":"1100","name":"John Stuart"}]

Code:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *jsonData = [responseData objectFromJSONData];
    NSString *name = [jsonData objectForKey:@"name"];
    NSLog(@"Name: %@", name);
}

Error:

** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[JKArray objectForKey:]: unrecognized selector sent to instance 0x84b9b30'

Solution

  • Your JSON is an array, but your code assumes it's a dictionary and tries to call -objectForKey: on it. You might want to try the following:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSArray *jsonData = [responseData objectFromJSONData];
        for (NSDictionary *dict in jsonData) {
            NSString *name = [dict objectForKey:@"name"];
            NSLog(@"Name: %@", name);
        }
    }