小编use*_*452的帖子

从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 …
Run Code Online (Sandbox Code Playgroud)

ios nsjsonserialization

7
推荐指数
1
解决办法
1757
查看次数

标签 统计

ios ×1

nsjsonserialization ×1