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文档和其他地方很好看,并没有找到任何直接确认上述.
| 归档时间: |
|
| 查看次数: |
1757 次 |
| 最近记录: |