【问题标题】:object returned from NSJSONSerialization can vary从 NSJSONSerialization 返回的对象可能会有所不同
【发布时间】:2012-10-18 03:20:42
【问题描述】:

以下陈述是否正确,还是我遗漏了什么?

你必须检查NSJSONSerialization的返回对象,看看它是字典还是数组——你可以有

data = {"name":"joe", "age":"young"}
// NSJSONSerialization returns a dictionary

data = {{"name":"joe", "age":"young"},
    {"name":"fred", "age":"not so young"}}
// returns an array

每种类型都有不同的访问方法,如果使用错误的方法会中断。 例如:

NSMutableArray *jsonObject = [json objectAtIndex:i];
// will break if json is a dictionary

所以你必须做类似 -

  id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData
      options:NSJSONReadingMutableContainers error:&error];

    if ([jsonObjects isKindOfClass:[NSArray class]])
        NSLog(@"yes we got an Array"); // cycle thru the array elements
    else if ([jsonObjects isKindOfClass:[NSDictionary class]])
         NSLog(@"yes we got an dictionary"); // cycle thru the dictionary elements
    else
          NSLog(@"neither array nor dictionary!");

我仔细查看了堆栈溢出和 Apple 文档和其他地方,但找不到上述任何直接确认。

【问题讨论】:

  • 你没有提到你的代码出了什么问题。
  • 问题是如果你得到一个字典并使用一个数组方法来访问它,就会抛出一个异常。我认为您需要检查返回对象类型来解决此问题,但想确认这是正确的方法。

标签: ios nsjsonserialization


【解决方案1】:

如果您只是询问这是否正确,是的,这是处理jsonObjects 的安全方式。这也是您使用其他返回 id 的 API 的方式。

【讨论】:

  • 好的 - 谢谢 - 关于使用 NSJSONSerialization 和不检查返回类型(或总是假设它不是变量)有很多问题是/曾经是(无论如何对我来说)一个微妙的问题.这篇文章的目的是确认和澄清。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 2021-05-28
相关资源
最近更新 更多