IOS Dev获取JSON数据

时间:2014-11-09 15:32:38

标签: ios objective-c iphone json dictionary

我是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?

1 个答案:

答案 0 :(得分:0)

您的示例中有一个小的逻辑错误。表达式[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];返回NSArray而不是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"];

回到您的示例,要从两个JSON对象中的第一个访问defaultGateway,您可以执行以下操作:

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