0

我正在尝试在 Objective-C 中解析 JSON,但遇到了麻烦。我正在关注的教程中的示例仅进入父节点之后的第一级。我正在尝试获取更深入的数据。关于如何做到这一点的任何建议?

我要获取的元素: 标题:data.children[i].data.title 缩略图:data.children[i].data.thumbnail Json:http ://www.reddit.com/r/HistoryPorn/.json

NSURL *blogURL = [NSURL URLWithString:@"http://www.reddit.com/r/HistoryPorn/.json"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];

NSError * error = nil;


NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

self.blogPosts = [NSMutableArray array];

NSArray * blogPostsArray = [dataDictionary objectForKey:@"data"];

for (NSDictionary *bpDictionary in blogPostsArray) {
    BlogPost * blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:@"title"]];
    blogPost.thumbnail = [bpDictionary objectForKey:@"thumbnail"];
    blogPost.url = [NSURL URLWithString:[bpDictionary objectForKey:@"url"]];
    [self.blogPosts addObject:blogPost];
}
4

1 回答 1

0

使用新语法应该更容易在嵌套字典中获取键。您只需绘制一棵树就可以知道完整的键/索引路径,请记住字典以大括号开头,而数组以括号开头。例如,让我们检索 children 数组中第一个条目的“thumbnail”和“url”值:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(!json)
{
    // Always handle eventual errors:
    NSLog(@"%@",error);
    return;
}
NSString* thumbnail= json[@"data"][@"children"][0][@"data"][@"thumbnail"];
NSString* url= json[@"data"][@"children"][0][@"data"][@"url"];
于 2013-06-21T23:01:53.443 回答