Objective c 如何在iPhone应用程序中使用JSON?

Objective c 如何在iPhone应用程序中使用JSON?,objective-c,json,weather,Objective C,Json,Weather,我正在尝试制作一个天气应用程序,我在网上找到了一个很棒的JSON天气API。我正在使用 NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: absoluteURL]]; NSError * error; NSDictionary * json = [NSJSONSerialization JSONObjectWithData: data //1 options: kNilOptions error:

我正在尝试制作一个天气应用程序,我在网上找到了一个很棒的JSON天气API。我正在使用

NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: absoluteURL]];
NSError * error;
NSDictionary * json = [NSJSONSerialization JSONObjectWithData: data //1
  options: kNilOptions 
  error: & error
];
NSLog(@"%@", json);
NSLog([NSString stringWithFormat: @"location: %@", [json objectForKey: @"status"]]);

要获取数据,但它无法工作,日志将返回
(null)
。有人能告诉我如何获取JSON文件的字符串和值吗?谢谢

编辑:将代码从第3行(包括)更改为:

NSLog()
s将显示
JSON响应中的所有位置

如果希望城市和国家只显示一次,则可以执行以下操作:

NSDictionary *location = json[@"objects"][0][@"location"];
NSString *country = location[@"country"];
NSString *locality = location[@"locality"];

NSLog(@"country: %@", country);
NSLog(@"locality: %@", locality);
输出:

国家:德国
地点:Hauzenberg

JSON的根目录中没有元素“status”。json对象将包含与json完全相同的层次结构。在您的情况下,它将如下所示:

root (dictionary)
  |
  -- "objects": (array)
        |
        -- (dictionary)
              |
              -- "sources" (array) 
              -- "weather" (dictionary)
...
你明白了

试试这个:

for (NSDictionary *object in json[@"objects"])
{
    NSLog([NSString stringWithFormat: @"location: %@", object[@"weather"][@"status"]]);
}

“错误”是什么?你做过任何基本的调试吗?@Wain错误是我想获取天气状态,而不是(null):)我喜欢在日志中记录天气状态,但是我添加了天气,所以你可以查看它的格式。你在JSONObjectWithData调用中传递的错误属性。在日志中打印。@HSA位置日志为(null),但json日志(NSLog(@“%@”,json))不是(nil)它显示了整个json脚本,因此我认为“扫描东西”有问题@HSA好的,慢慢来,请检查我添加到帖子中的API URL,以便您可以看到其结构@Maroux好的,它可以工作,但是JSON脚本有11个状态,我只需要第一个,有没有办法将11个不同的状态作为11个字符串?
for (NSDictionary *object in json[@"objects"])
{
    NSLog([NSString stringWithFormat: @"location: %@", object[@"weather"][@"status"]]);
}