1

I'm trying to reference a Twitter username using Json and ObjectForKey

Example twitter JSON

source = web;
user =         {
        "contributors_enabled" = 0;
        "created_at" = "Tue Mar 09 11:36:02 +0000 2010";
        "default_profile" = 0;
        "default_profile_image" = 0;
        description = "Welcome to the Official Twitter page for Tottenham Hotspur Football Club, where you can get your official Club news, competitions and more!";
        "favourites_count" = 97;
        "follow_request_sent" = "<null>";
        "followers_count" = 360893;
        following = 1;
        "friends_count" = 80;
        "geo_enabled" = 0;
        id = 121402638;
        "id_str" = 121402638;
        "is_translator" = 0;
        lang = en;
        "listed_count" = 3514;
        location = "Tottenham, London, England";
        name = "Tottenham Hotspur";
}

Now I want to use the key name within user but have no clue how to reference it. I know if I wanted to use the source I could use

objectForKey:@"source"

but do not know what to put down for user:name

2
  • 2
    [[... objectForKey:@"user"] objectForKey:@"name"] Commented Jan 30, 2013 at 19:55
  • Forget that it's JSON. You're dealing with NSDictionaries nested one inside the other. Peel the onion. Commented Jan 30, 2013 at 20:46

1 Answer 1

5

For the sake of education, an alternative would be to use the key-value coding mechanisms exposed via valueForKeyPath:.

Per the key-value coding fundamentals, valueForKeyPath: breaks down the supplied path by separating full stops and calls valueForKey: progressively on each member. So, e.g. the following are equivalent:

[obj valueForKeyPath:@"ted.jefferson"]
[[obj valueForKey:@"ted"] valueForKey:@"jefferson"]

Furthermore, NSDictionary implements its valueForKey: directly to call objectForKey: unless you've added an @ to access metadata rather than content. So in this case it is safe to substitute the one for the other, given that you're using string keys.

Therefore the most abbreviated way to do what you want is:

[obj valueForKeyPath:@"user.name"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.