Question

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'
Était-ce utile?

La 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);
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top