我正在尝试制作天气应用程序,我在网上找到了一个很棒的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文件的字符串和值吗?谢谢!
答案 0 :(得分:2)
编辑:将代码从第3行(包括)更改为:
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *meta = json[@"objects"];
for (NSDictionary *aDict in meta) {
NSDictionary *location = aDict[@"location"];
NSLog(@"%@", location);
}
NSLog()
中JSON response
的所有位置city
。{/ 1>
如果您想要country
和NSDictionary *location = json[@"objects"][0][@"location"];
NSString *country = location[@"country"];
NSString *locality = location[@"locality"];
NSLog(@"country: %@", country);
NSLog(@"locality: %@", locality);
,只需执行以下操作:
{{1}}
<强>输出:强>
国家:德国
地点:Hauzenberg
答案 1 :(得分:0)
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"]]);
}