parse JSON weather object from Open Weather Map API using AFNetworking

I am using AFNetworking to retrieve information about the weather for a specific location, e.g:

http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}

I am using the AFNetworking framework but I am having the problems parsing some objects of the JSON.

If I have an NSDictionary with the MAIN object information from the JSON:

NSDictionay *main = [responseObject objectForKey:@"main"];

If I log the main NSDictionary I will get the following valid output:

"main":{  
      "temp":296.78;
      "pressure":1011;
      "humidity":69;
      "temp_min":293.15;
      "temp_max":299.82
   };

Although if I create a NSDictionary containing the weather object I will get the following information whenever logging it to the console:

NSDictionay *weather = [responseObject objectForKey:@"weather"];

"weather":(  
      {  
         "id":801;
         "main":"Clouds";
         "description":"few clouds";
         "icon":"02d"
      }
   );

The parsed information contains ( brackets instead of [ from the original response. This does not allow me to correctly access the inside attributes of the weather object.

Summing up, I am able to access all the inside variables of the MAIN object, but I cannot access the attributes of the Weather object (e.g access the icon attribute).

Can someone help me with this ?

Thank you,

Upvotes: 3

Views: 1658

Answers (1)

Kirit Modi
Kirit Modi

Reputation: 23407

You calling your service as below.

    NSString *query = @"http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}";

    NSLog(@"%@",query);
    query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;

Now print Response :

NSLog(@"weather==%@",[results objectForKey:@"weather"]);

NSLog(@"description==%@",[[[results objectForKey:@"weather"] objectAtIndex:0] objectForKey:@"description"]);

NSLog(@"icon==%@",[[[results objectForKey:@"weather"] objectAtIndex:0] objectForKey:@"icon"]);

NSLog(@"id==%@",[[[results objectForKey:@"weather"] objectAtIndex:0] objectForKey:@"id"]);

NSLog(@"main==%@",[[[results objectForKey:@"weather"] objectAtIndex:0] objectForKey:@"main"]);

Your Response is :

whwather==(
{
description = "sky is clear";
icon = 01d;
id= 800;
main= Clear;
}
)

description== "sky is clear";
icon == 01d;
id == 800;
main == Clear;

Upvotes: 2

Related Questions