Search code examples
jsoncocoaparsingfeed

Accessing JSON feed data


I have an iOS app set up to download and parse a JSON feed. It fetches data fine, but I am struggling on how to read certain nested JSON data of the feed.

Here is the JSON feed I am trying to load: http://api.wunderground.com/api/595007cb79ada1b1/conditions/forecast/q/51.5171,0.1062.json

The part of the JSON feed I am trying to load is:

"forecast":{
    "txt_forecast": {
    "date":"1:00 AM BST",
    "forecastday": [
    {
    "period":0,
    "icon":"chancerain",
    "icon_url":"http://icons-ak.wxug.com/i/c/k/chancerain.gif",
    "title":"Thursday",
    "fcttext":"Clear with a chance of rain in the morning, then mostly cloudy with a chance of rain. High of 59F. Winds from the SSE at 5 to 10 mph. Chance of rain 60%.",
    "fcttext_metric":"Clear with a chance of rain in the morning, then mostly cloudy with a chance of rain. High of 15C. Winds from the SSE at 5 to 15 km/h. Chance of rain 60%.",
    "pop":"60"
    }

You see there is a bit called "period":0 and in period 0 there is "icon", "title" etc...

Well I am trying to access that data but I can't.

Here is my code for accessing a certain part of the nested JSON feed:

NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves  error:&myError];
NSArray *results = [res objectForKey:@"current_observation"];
NSArray *cur = [results valueForKey:@"weather"];
NSArray *windrep = [results valueForKey:@"wind_string"];
NSArray *UVrep = [results valueForKey:@"UV"];
NSArray *othertemprep = [results valueForKey:@"temperature_string"];
NSString *loc = [[results valueForKey:@"display_location"] valueForKey:@"city"];
NSString *countcode = [[results valueForKey:@"display_location"] valueForKey:@"country"];

How can I change that to access what I want?

Here is my other attempt:

 NSString *test = [[[results valueForKey:@"forecast"] valueForKey:@"period:0"] valueForKey:@"title"];

Thanks for your help, Dan.


Solution

  • period is just a key in the first dictionary contained in the forecastday array, with a value of 0. It doesn't identify the dictionary in any way.

    To get the title value in the first element of forecastday, your code should look like this:

    NSString *title = results[@"forecast"][0][@"title"];
    

    Or, if you're not using the new subscripting syntax:

    NSString *title = 
      [[[results objectForKey:@"forecast"] objectAtIndex:0] objectForKey:@"title"];