Objective-C : How to read JSON in JSON?

标签 objective-c ios json

我有这样的 JSON:

 {
       "destination_addresses" : [ "Dimitrov, Phnom Penh, Cambodia" ],
       "origin_addresses" : [ "Tchecoslovaquie, Phnom Penh, Cambodia" ],
       "rows" : [
          {
             "elements" : [
                {
                   "distance" : {
                      "text" : "0.6 km",
                      "value" : 594
                   },
                   "duration" : {
                      "text" : "2 mins",
                      "value" : 100
                   },
                   "status" : "OK"
                }
             ]
          }
       ],
       "status" : "OK"
    }

这是我的代码:

SBJsonParser *parser = [[SBJsonParser alloc] init]; 
NSDictionary *data = (NSDictionary *) [parser objectWithString:apiResponse error:nil]; 
NSLog(@"Data = %@",data);

// getting the data from inside of "rows"  
NSDictionary *rows = (NSDictionary *) [data objectForKey:@"rows"];  
NSLog(@"Row = %@",rows);

NSDictionary *element = (NSDictionary *) [rows objectForKey:@"elements"];
NSLog(@"elements = %@",element);

NSDictionary *distance = (NSDictionary *) [rows objectForKey:@"distances"];
NSLog(@"Distance = %@",distance);

但出现错误:

-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x5a9afa0 with NSDictionary *element = (NSDictionary *) [rows objectForKey:@"elements"];

我想获取距离键的值!

最佳答案

如果你仔细观察,rows是一个数组内部的字典。

"rows" : [
          {
             "elements" : [
                {
                   "distance" : {
                      "text" : "0.6 km",
                      "value" : 594
                   },
                   "duration" : {
                      "text" : "2 mins",
                      "value" : 100
                   },
                   "status" : "OK"
                }
             ]
          }
       ]

所以你需要做

NSArray *rows          = [data objectForKey:@"rows"];  
NSDictionary *rowsDict = [rows objectAtIndex:0];

NSArray *element = [rowsDict objectForKey:@"elements"];
NSLog(@"elements = %@",element);

NSDictionary *distance = [[element objectAtIndex:0] objectForKey:@"distances"];
NSLog(@"distance= %@", distance);

等等等等。

NSLog(@"Distance = %@",distance);

关于 Objective-C : How to read JSON in JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7802445/

相关文章:

iphone - Objective-C 属性 setter 如何发出失败信号?

ios - 何时创建自定义数据源方法而不是设置变量

json - 我应该如何在 Spring Message Converters Objectmapper 上设置功能?

ios - Swift 如何更新(修改、删除、添加)JSON 条目

objective-c - 在 Swift 中声明具有泛型类型的变量

objective-c - swift : Alternative to . classForCoder()

ios - 是否可以在越狱的 iOS 设备上编译 X86 程序?

java - GSON - Json 到 Java 解析 - 如何保留尾随零

ios - UIImageView 正在显示放大的图像

ios - iPhone 数字时钟