以下陈述是否正确,或者我遗失了什么?
你必须检查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文档以及其他地方看得很清楚,但是找不到上面的任何直接确认。
答案 0 :(得分:5)
如果你只是问这是否正确,是的,这是处理jsonObjects
的安全方法。这也是您使用返回id
的其他API的方式。