【问题标题】:How to use JSON for an iPhone app?如何将 JSON 用于 iPhone 应用程序?
【发布时间】:2013-04-19 16:07:32
【问题描述】:

我正在尝试制作一个天气应用程序,我在网上找到了一个很棒的 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 文件的字符串和值吗?谢谢!

【问题讨论】:

  • “错误”中有什么内容?你做过基本的调试吗?
  • @Wain 错误是我想获取天气状态而不是(空):) 我喜欢在日志中记录天气状态,而不是例如多云我得到(空)我添加了天气,所以你可以看看它是如何格式化的。
  • 您在 JSONObjectWithData 调用中传递的错误属性。在日志中打印出来。

标签: objective-c json weather


【解决方案1】:

编辑:将您的代码从第 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()s 是你JSON response 中的所有位置。

如果您只需要 citycountry 一次,您可以执行以下操作:

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

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

输出:

国家:德国
地点:豪岑贝格

【讨论】:

  • @HSA 位置日志为 (null),但 json 日志 ( NSLog(@"%@", json) ) 不是 (nil) 它显示了整个 JSON 脚本,所以我认为“扫描的东西”有问题
  • @HSA 好的,慢慢来,请查看我在帖子中添加的API URL,以便您看到编队!
【解决方案2】:

JSON 的根目录中没有元素“状态”。 json 对象将包含与 JSON 完全相同的层次结构。在你的情况下,它看起来像这样:

root (dictionary)
  |
  -- "objects": (array)
        |
        -- (dictionary)
              |
              -- "sources" (array) 
              -- "weather" (dictionary)
...

你明白了。

试试这个:

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

【讨论】:

  • @Maroux 好的,它可以工作,但是 JSON 脚本有 11 个状态,我只需要第一个,有没有办法将 11 个不同的雕像作为 11 个字符串?
猜你喜欢
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2011-07-10
  • 2011-05-21
  • 2023-03-15
  • 1970-01-01
  • 2011-08-17
相关资源
最近更新 更多