我是IOS开发人员的新手,我确实需要一些帮助。
我想解析(正在工作)并获取一些JSON数据。我将本教程用于http请求和json解析http://www.mysamplecode.com/2013/04/ios-http-request-and-json-parsing.html
一维字典一切正常
但我需要能够获取以下JSON数据
[{"defaultGateway": "10.10.10.254", "hostname": "On", "connected": "true", "subnetMask": "255.255.255.255", "iPAddress": "10.10.10.10", "dhcpEnabled": "true"},
{"defaultGateway": "10.10.10.254", "hostname": "On", "connected": "true", "subnetMask": "255.255.255.255", "iPAddress": "10.10.10.10", "dhcpEnabled": "true"}]
使用以下函数后,我得到了以下字典,但我真的不知道该如何访问
NSDictionary * res = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
这是字典的图片http://www11.pic-upload.de/09.11.14/5n4hdg3eh84q.png
例如,如何访问第一本词典中的defaultGateway?
您的示例中有一个小逻辑错误。该表达式[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
返回一个NSArray
and而不是and NSDictionary
。因此,首先您应该将这一部分更改为:
NSArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
我知道这是一个数组,因为您的JSON字符串包含两个JSON对象的数组。NSJSONSerialization
会将JSON数组转换为类型的对象,NSArray
并将JSON对象转换为类型的对象NSDictionary
。
如果不确定JSON包含什么,可以执行以下操作:
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if ([result isKindOfClass:[NSArray class]]){
// do something with the array
}
else if ([result isKindOfClass:[NSDictionary class]]){
// do something with the dictionary
}
对于您的问题,您可以NSDictionary
通过提供密钥来访问中的数据,可以通过两种方式进行操作:
NSString *gateway = [dictionary objectForKey:@"defaultGateway"];
甚至更快:
NSString *gateway = dictionary[@"defaultGateway"];
回到您的示例,defaultGateway
要从两个JSON对象中的第一个访问,您可以执行以下操作:
NSArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; // parse the JSON and store in array
NSDictionary *dict = result[0]; // take the first of the two JSON objects and store it in a dictionary
NSString *gateway = dictionary[@"defaultGateway"]; // retrieve the defaultGateway property
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句