Parse JSON weather object from open weather Map API using AFNetworking

I am using AFNetworking to get weather information for a specific location, for example:

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

      

I am using the AFNetworking framework, but I am having trouble parsing some JSON objects.

If I have NSDictionary with MAIN object information from JSON:

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

      

If I register the main NSDictionary, I 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 an NSDictionary containing a weather object, I get the following information when I log into 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 answer. This prevents me from accessing the internal attributes of the weather object correctly.

To summarize, I can access all the internal variables of the MAIN object, but I cannot access the attributes of the Weather object (for example, access the icon icon).

Can anyone help me?

Thank,

+3


source to share


1 answer


You are calling your service as shown 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 your answer:



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 Answer:

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

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

      

+2


source







All Articles