筛选 NSMutableArray 中的 JSON 个项目

Filter JSON items in NSMutableArray

我有一个小问题,我有一个 json 提要,我想在一个数组中显示其国家/地区 = 法国的项目怎么办?谢谢
(Objective-C)
我的 JSON :

    { 
  "menu": "Fichier", 
  "commandes": [ 
      {
          "country": "France", 
          "city": "Paris"
      }, 
      {
          "country": "USA", 
          "city": "New York"
      }, 
      {
          "country": "Canada",
          "city": "Quebec"
      }
   ] 
} 

这将有助于:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"commandes" ascending:TRUE];
[sourceArr sortUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

首先使用 NSJSONSerialization

解析你的 JSON 数据
// data will be your Json NSData

 NSError* jsonError;
 NSDictionary* jsonDictn = [NSJSONSerialization JSONObjectWithData:data
                             options:kNilOptions
                             error:&error];
 NSMutableArray * aray = [[jsonDictn objectForKey:@"commandes"] mutableCopy];
 for (NSDictionary* tmpdictn in aray) {
     NSString * tmpstr = [tmpdictn objectForKey:@"country"];
     if (![tmpstr isEqualToString:@"France"]) {
         [aray removeObject:tmpdictn];
      }
 }
 NSLog(@"aray: %@",aray);

您需要使用 NSPredicate 从数组

中搜索数据

使用下面的代码

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"country == %@", @"France"];
NSArray *filteredArray = [[arr objectForKey:@"commandes"] filteredArrayUsingPredicate:predicate];