0

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);

}
3
  • 2
    Print the jsonString and the json array to the console (via NSLog). This should give you the idea what is going wrong. Presumably it the response from the URL not an array but a dictionary. Commented Nov 19, 2013 at 11:42
  • Why you putting the data into an array it should go into a dictionary? Commented Nov 19, 2013 at 11:47
  • NSMutableArray *children = [[json valueForKey:@"data"] valueForKey:@"children"]; NSMutableArray *titles = [children valueForKeyPath:@"data.title"]; Commented Nov 19, 2013 at 12:00

1 Answer 1

1

Looking at the JSON object returned in that pastebin, you get the following:

    {
        "kind":"Listing",
        "data":{
        "modhash":"",
        "children":[ ... ],
        "after":"t3_1qwcm7",
        "before":null
        }
    }

That is not an array, its a JSON object.. To get the titles of the children you would want to do the following:

    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSMutableArray *children = [[json objectForKey:@"data"] objectForKey:@"children"];
    NSMutableArray *titles = [children valueForKeyPath:@"data.title"];

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 of valueForKey: because the data is nested in another object

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.