【问题标题】:IOS Dev Fetching JSON DataIOS 开发者获取 JSON 数据
【发布时间】:2014-11-09 15:32:37
【问题描述】:

我是 IOS dev 的新手,我真的需要一些帮助。

我想解析(正在工作)并获取一些 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?

【问题讨论】:

  • 访问 json.org 并学习 JSON 语法。学习只需5-10分钟。然后观察一个 JSON 数组映射到一个 NS(Mutable)Array,一个 JSON 对象映射到一个 NS(Mutable)Dictionary。来自 NSLog 的 NSArray 转储由() 括起来,而 NSDictionary 转储由{} 括起来。现在查看res 的 NSLog 转储并告诉我你有什么。 (调试器显示具有欺骗性。)
  • 我使用 NSLog www11.pic-upload.de/09.11.14/xp5sttdy3u2m.png得到了以下转储
  • 你会看到“最外面”的括号是(),这意味着最外面的对象是一个NS(Mutable)Array,而不是字典。

标签: ios objective-c iphone json dictionary


【解决方案1】:

您的示例中有一个小的逻辑错误。表达式 [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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多