【发布时间】: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 文档和其他地方,但找不到上述任何直接确认。
【问题讨论】:
-
你没有提到你的代码出了什么问题。
-
问题是如果你得到一个字典并使用一个数组方法来访问它,就会抛出一个异常。我认为您需要检查返回对象类型来解决此问题,但想确认这是正确的方法。