从NSJSONSerialization返回的对象可能会有所不同

use*_*452 7 ios nsjsonserialization

以下陈述是正确的,还是我错过了什么?

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

data = {"name":"joe", "age":"young"}
// NSJSONSerialization returns a dictionary
Run Code Online (Sandbox Code Playgroud)

data = {{"name":"joe", "age":"young"},
    {"name":"fred", "age":"not so young"}}
// returns an array
Run Code Online (Sandbox Code Playgroud)

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

NSMutableArray *jsonObject = [json objectAtIndex:i];
// will break if json is a dictionary
Run Code Online (Sandbox Code Playgroud)

所以你必须做一些像 -

  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!");
Run Code Online (Sandbox Code Playgroud)

我通过堆栈溢出和Apple文档和其他地方很好看,并没有找到任何直接确认上述.

Joh*_*pia 5

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