How do I access JSON data in an NSMutableArray?

2019-06-14 17:45发布

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

}

1条回答
做个烂人
2楼-- · 2019-06-14 18:13

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

查看更多
登录 后发表回答