使用AFNetworking从Open Weather Map API解析JSON天气对象

时间:2015-08-03 12:58:17

标签: ios objective-c json

我正在使用AFNetworking检索有关特定位置的天气信息,例如:

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

我正在使用AFNetworking框架,但我遇到了解析JSON的一些对象的问题。

如果我有一个带有来自JSON的MAIN对象信息的NSDictionary:

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

如果我记录主NSDictionary,我将得到以下有效输出:

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

虽然如果我创建一个包含天气对象的NSDictionary,我会在将其记录到控制台时获得以下信息:

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

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

解析后的信息包含(括号而不是[来自原始响应。这不允许我正确访问天气对象的内部属性。

总结一下,我能够访问MAIN对象的所有内部变量,但是我无法访问Weather对象的属性(例如访问图标属性)。

有人可以帮我这个吗?

谢谢,

1 个答案:

答案 0 :(得分:2)

您按以下方式致电服务。

    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;

现在打印响应:

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"]);

您的回复是:

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

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