Objective-C: The Easiest Way To Parse Nested Dictionaries

For the past two weeks, I’ve been working a lot with APIs, which of course are in the JSON format and usually have dictionaries inside of dictionaries inside of dictionaries.

Let’s take a look at the App.net public api. An example app.net update will look something like this:

{
    "created_at": "2013-05-25T03:39:05Z",
    "num_stars": 0,
    "num_replies": 0,
    "source": {
        "link": "http://riposteapp.net",
        "name": "Riposte",
        "client_id": "737a54nLCdLLutcs2VzhtNKGnnMrakc4"
    },
    "text": "We need new rules for using acronyms. If googling an acronym does not find it in the first few links, you should spell it out instead.",
    "num_reposts": 0,
    "id": "6027821",
    "entities": {
        "mentions": [],
        "hashtags": [],
        "links": []
    },
    "html": "We need new rules for using acronyms. If googling an acronym does not find it in the first few links, you should spell it out instead.",
    "machine_only": false,
    "user": {
        "username": "jrinn",
        "avatar_image": {
            "url": "https://d2rfichhc2fb9n.cloudfront.net/image/5/eGiW2i1Ziwn9i1YyM5jE99Wwat97InMiOiJzMyIsImIiOiJhZG4tdXNlci1hc3NldHMiLCJrIjoiYXNzZXRzL3VzZXIvZGQvMDIvMzAvZGQwMjMwMDAwMDAwMDAwMC5qcGciLCJvIjoiIn0",
            "width": 200,
            "is_default": false,
            "height": 200
        },
        "description": {
            "text": "iPhone app developer and father.",
            "html": "iPhone app developer and father.",
            "entities": {
                "mentions": [],
                "hashtags": [],
                "links": []
            }
        },
        "locale": "en_US",
        "created_at": "2013-04-02T06:23:09Z",
        "canonical_url": "https://alpha.app.net/jrinn",
        "cover_image": {
            "url": "https://d2rfichhc2fb9n.cloudfront.net/image/5/kZ-JRmTbmd3WVPswTJ8Nwxzkf917InMiOiJzMyIsImIiOiJ0YXBwLWFzc2V0cyIsImsiOiJpL1UvaS9ZL1VpWW5xRFNvTUtyTEhLNXA0OHN2NkxmTmRVMC5qcGciLCJvIjoiIn0",
            "width": 960,
            "is_default": true,
            "height": 260
        }
    }
}

Let’s say you want to get the avatar url. Normally, you would do it using the objectForKey: method, like this:

NSString *avatarURL = [[[dictionary objectForKey:@"user"]
                            objectForKey:@"avatar_image"]
                            objectForKey:@"url"];

Well, apparently, you can also use the NSKeyValueCoding Protocol for Dictionaries, which includes the method called valueForKeyPath:. So to get the avatar url with this method will now be a lot cleaner:

NSString *avatarURL = [dictionary valueForKeyPath:@"user.avatar_image.url"];

Nice, right?!! What are some of your favorite methods for parsing dictionaries?

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.