Steaphann
Steaphann

Reputation: 2777

json is not parsing correctly in objective-c

I'm trying to parse my JSON into an NSDictionary. Here is the method that I use for parsing.

+ (NSDictionary *)executeGenkFetch:(NSString *)query
{
    query = [NSString stringWithFormat:@"%@", query];
    query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSLog(@"[%@ %@] sent %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), query);
    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;
    if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
     NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results);
    return results;
}

And here is how I use this function.

+(NSArray *)getCommentsWithParam:(NSString *)Param
{
    NSString *request = [NSString stringWithFormat:@"https://graph.facebook.com/comments/?ids=%@",Param];
    NSLog(@"request is %@",request);
    NSString *vfk = [NSString stringWithFormat:@"%@.comments.data",Param];
    return [[self executeGenkFetch:request] valueForKey:vfk];
}

The problem is when I log the NSArray that I get back from getCommentsWithParam, I always get NULL. But when I look at the log from

 NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results);

I get the JSON I want. Any help on what is going wrong?

Upvotes: 0

Views: 149

Answers (1)

Martin R
Martin R

Reputation: 539685

It is difficult to say without seeing the actual JSON data, but probably in

NSString *vfk = [NSString stringWithFormat:@"%@.comments.data",Param];
return [[self executeGenkFetch:request] valueForKey:vfk];

you have to use valueForKeyPath instead of valueForKey, because vfk is a key path with several key components (separated by the dots).

Update: Another problem is that the top-level key Param is a HTTP URL and contains dots. But in key-value coding dots are used to separate the key components. Therefore you cannot use Param as a key component. Use objectForKey for the top-level key instead:

NSDictionary *results = [self executeGenkFetch:request];
return [[results objectForKey:Param] valueForKeyPath:@"comments.data"];

Upvotes: 5

Related Questions