Say you make a call to a web service of some kind and you get a response that looks like this:

"forecast":  {
    "txt_forecast":  {
        "date": "6:00 AM MDT",
        "forecastday":  [
                         {
                             "period": 0,
                             "icon": "mostlycloudy",
                         },

And you want to get some nested element like ‘icon’. Here’s one way you can do it:


success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
                                             
NSString *icon = [json 
valueForKeyPath:@"forecast.txt_forecast.forecastday.icon"];
}

The network library AFNetworking (highly recommended) returns a json object which is a NSDictionary.

You can treat this dictionary like any other NSDictionary and grab subelements using ‘valueForKeyPath’
Thanks Dave Anderson and Paul Thorsteinson for showing me this.

About these ads