IOS开发人员获取JSON数据

amor91

我是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];返回一个NSArrayand而不是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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

ios企业开发人员帐户

来自分类Dev

为iOS开发人员启动Android开发

来自分类Dev

为企业开发iOS作为个人开发人员

来自分类Dev

开发人员证书

来自分类Dev

JSON使用$ http提取数据在phonegap开发人员应用中不起作用

来自分类Dev

AWS开发人员门户-TypeError:无法获取

来自分类Dev

获取贝宝开发人员文档

来自分类Dev

从开发人员工具获取端口

来自分类Dev

iOS开发人员计划证书转移

来自分类Dev

iOS 10升级开发人员清单

来自分类Dev

如何通过代码访问iOS开发人员证书

来自分类Dev

验证后端的ios开发人员帐户

来自分类Dev

验证后端的ios开发人员帐户

来自分类Dev

iOS在开发人员门户中添加设备

来自分类Dev

iOS Apple开发人员应用指南

来自分类Dev

从开发人员工具隐藏API数据

来自分类Dev

SQL开发人员插入数据错误

来自分类Dev

Android开发人员:同步数据库

来自分类Dev

在iOS开发人员程序中使用其他名称作为开发人员名称

来自分类Dev

如何通过javascript在chrome开发人员控制台中获取自动完成数据?

来自分类Dev

Windows 10开发人员模式

来自分类Dev

Firefox开发人员版本TypeError

来自分类Dev

android:隐藏开发人员选项

来自分类Dev

自动构建单个开发人员

来自分类Dev

Linux上的SQL开发人员

来自分类Dev

时代-开发人员证书问题

来自分类Dev

eBay开发人员改进

来自分类Dev

Android每个开发人员变量

来自分类Dev

Chisel开发人员指南?