I'm trying to access JSON data that I have taken from a website and stored in an array. First, however, I want to filter out everything but the "title" information, which I am doing using the valueForKey:
method. In order to test this I am writing them to the log using the NSLog
method, however when I run this I get "null".
Can anyone advise me, as to why I'm getting what I'm getting?
Thanks for your help, much appreciated.
{
NSURL *redditURL = [NSURL URLWithString:@"http://pastebin.com/raw.php?i=FHJVZ4b7"];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:redditURL encoding:NSASCIIStringEncoding error:&error];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSMutableArray *titles = [json valueForKey:@"title"];
NSLog(@"%@", json);
}
Looking at the JSON object returned in that pastebin, you get the following:
That is not an array, its a JSON object.. To get the titles of the children you would want to do the following:
This is because the children array is nested in a
"data"
object and each individual child object is nested in another"data"
object.You then also need to call
valueForKeyPath:
instead ofvalueForKey:
because the data is nested in another object