【问题标题】:Objective-C : How to read JSON in JSON?Objective-C:如何在 JSON 中读取 JSON?
【发布时间】:2011-10-18 04:31:41
【问题描述】:

我有这样的 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:]: 无法识别的选择器发送到实例 0x5a9afa0 与 NSDictionary *element = (NSDictionary *) [rows objectForKey:@"elements"];

我想获得距离键值

【问题讨论】:

    标签: objective-c ios json


    【解决方案1】:

    如果你仔细观察,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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多