如何通过字典键过滤字典数组

时间:2014-07-19 10:55:17

标签: ios objective-c json ios7

这是我的JSON。这是我在下面仅列出3个国家的250个国家。在这里,我需要做的就是将各国分解为基于大陆的七个不同阵列。

{
  "geonames" : [
    {
      "languages" : "ca",
      "east" : 1.786542777831983,
      "continent" : "EU",
      "geonameId" : 3041565,
      "population" : "84000",
      "areaInSqKm" : "468.0",
      "countryName" : "Andorra",
      "south" : 42.42849259876837,
      "countryCode" : "AD",
      "capital" : "Andorra la Vella",
      "isoAlpha3" : "AND",
      "fipsCode" : "AN",
      "isoNumeric" : "020",
      "west" : 1.407186714111276,
      "continentName" : "Europe",
      "north" : 42.65604389629997,
      "currencyCode" : "EUR"
    },
    {
      "languages" : "ar-AE,fa,en,hi,ur",
      "east" : 56.38166046142578,
      "continent" : "AS",
      "geonameId" : 290557,
      "population" : "4975593",
      "areaInSqKm" : "82880.0",
      "countryName" : "United Arab Emirates",
      "south" : 22.63332939147949,
      "countryCode" : "AE",
      "capital" : "Abu Dhabi",
      "isoAlpha3" : "ARE",
      "fipsCode" : "AE",
      "isoNumeric" : "784",
      "west" : 51.58332824707031,
      "continentName" : "Asia",
      "north" : 26.08415985107422,
      "currencyCode" : "AED"
    },
    {
      "languages" : "fa-AF,ps,uz-AF,tk",
      "east" : 74.879448,
      "continent" : "AS",
      "geonameId" : 1149361,
      "population" : "29121286",
      "areaInSqKm" : "647500.0",
      "countryName" : "Afghanistan",
      "south" : 29.377472,
      "countryCode" : "AF",
      "capital" : "Kabul",
      "isoAlpha3" : "AFG",
      "fipsCode" : "AF",
      "isoNumeric" : "004",
      "west" : 60.478443,
      "continentName" : "Asia",
      "north" : 38.483418,
      "currencyCode" : "AFN"
    }
  ]
}

2 个答案:

答案 0 :(得分:2)

这是您过滤geonames数组的方法。方法filterArrayByADictionary获取数组和搜索条件,并返回过滤的字典数组。

-(NSArray *)filterArrayByADictionary:(NSArray *)aArray andKey:(NSString *)aPredicte
{
    NSPredicate *filter = [NSPredicate predicateWithFormat:aPredicte];
    return [aArray filteredArrayUsingPredicate:filter];
}

你可以像这样调用这个方法。

NSArray *AsiaCounties =  [self filterArrayByADictionary: geonames andKey:@"continent = 'AS'"];
NSArray *EuropeCounties =  [self filterArrayByADictionary: geonames andKey:@"continent = 'EU'"];
// rest of the continents...

答案 1 :(得分:-2)

假设您已在NSDictionary中使用此输出:

NSDictionary *mainDic;

NSMutableArray *arr = [NSMutableArray new];
NSMutableArray *arrcontinent1 = [NSMutableArray new];
NSMutableArray *arrcontinent2 = [NSMutableArray new];

arr = [mainDic valueForKey:@"geonames"];

for(int i=0; i<[arr count];i++){
    NSDictionary *dic = [arr objectAtIndex:i];
    if([[dic valueForKey:@"continent"] isEqualToString:@"EU"]){
        [arrcontinent1 addObject:dic];
    }
    else if([[dic valueForKey:@"continent"] isEqualToString:@"AS"]){
        [arrcontinent2 addObject:dic];
    }
//        and so on......
}