如何在具有相同Key的其他值之间获取特定值

时间:2012-01-29 17:16:47

标签: objective-c ios json

我的JSON响应是这样的:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "285",
               "short_name" : "285",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Bedford Ave",
               "short_name" : "Bedford Ave",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Williamsburg",
               "short_name" : "Williamsburg",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Brooklyn",
               "short_name" : "Brooklyn",
               "types" : [ "sublocality", "political" ]
            },

我需要获取Key long_name的最后一个值:

{
                   "long_name" : "Brooklyn",//i need to get this "Brooklyn"
                   "short_name" : "Brooklyn",
                   "types" : [ "sublocality", "political" ]
                },

虽然有很多值具有相同的键long_name

,但我怎么能得到它
NSArray *resultsArray = [responseDict objectForKey:@"results"];//what to do next?

1 个答案:

答案 0 :(得分:3)

[[[[[resultsArray objectAtIndex:0] valueForKey:@"address_components"] valueForKey:@"long_name"] lastObject];

分解:

// get array of address components
[[resultsArray objectAtIndex:0] valueForKey:@"address_components"]

// calling this on array will get you long_name values from ALL elements
...] valueForKey:@"long_name"]

// finally grab the last element long_name array
...] lastObject];

等同于:

[[[[resultsArray objectAtIndex:0] valueForKey:@"address_components"] lastObject] valueForKey:@"long_name"];

分解:

// get array of address components
[[resultsArray objectAtIndex:0] valueForKey:@"address_components"]

// get last dictionary
...] lastObject]

// get long_name from last dictionary
...] valueForKey:@"long_name"]