Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

iOS blog reader app: access JSON in another category

Hi all,

I'm adjusting the blog reader app code to my own wordpress website.

By using the JSON API plugin, my blog has the correct JSON data. However, my author and date info is not parsing correctly, because the author name is not in the same category as in the tutorial:

tutorial: JSON -> posts -> author

mypage: JSON -> posts -> author -> name

Now how can I change this in my code?

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

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

basically, for two of the objects i need to 'dig' one level deeper, but I can't find the right syntax to do so.

Any help would be greatly appreciated!

1 Answer

Try chaining them. It'll make the code shorter and looks neater. You can try using valueForKeyPath to do so.

So for your case, it should be something like this:

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

for (NSDictionary *bpDictionary in blogPostsArray) {
    BlogPost *blogPost = [BlogPost blogPostWithTitle: [bpDictionary objectForKey:@"title"]];
    blogpost.authorPostName = [bpDictionary valueForKeyPath: @"author.name"];
    [self.blogPosts addObject:blogPost];
}

Exactly what I needed. Thanks a lot!