0

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'
Luciano Nascimento
  • 2,600
  • 2
  • 44
  • 80
  • The very first line you copied from an example somewhere is wrong. The outermost JSON structure is an "array" as indicated by the surrounding `[]` characters. – Hot Licks Feb 13 '13 at 02:32

1 Answers1

2

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);
    }
}
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347