如何在objective-c中解析多个json?

时间:2013-06-21 22:19:24

标签: objective-c json

我试图在objective-c中解析JSON,但遇到了麻烦。我所遵循的教程中的示例仅转到父节点之后的第一级。我试图获得更深入的数据。关于如何做到这一点的任何建议?

我想要的元素: 标题:data.children [i] .data.title 缩略图:data.children [i] .data.thumbnail 杰森: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];
}

1 个答案:

答案 0 :(得分: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"];