2016-01-21 27 views
-2

我有一個小問題,我有一個json提要,我想在數組中顯示其國家=法國的項目怎麼辦?謝謝
(Objective-C的)
我的JSON:
在NSMutableArray中過濾JSON項目

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

請檢查這個環節,我希望它有助於[過濾的NSMutableArray(http://stackoverflow.com/questions/110332/filtering-nsarray-into-a-new-nsarray- in-objective-c) –

回答

0

你需要使用解析您的JSON數據NSPredicate來搜索數組中的數據

下面的代碼

使用

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

當我通過「Fra」並獲得「France」對象時,是否可以獲取數組? –

+0

不,這個謂詞不適用於這種查詢。你需要尋找包含謂詞的種類。 –

+0

好的,謝謝。 –

0

這將幫助:

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

首先使用NSJSONSerialization

// 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); 
+1

如果您已經創建了數組,並且只想添加使用NSPredicate的過濾器,則此代碼僅從實際Json獲取法國數組。 – Dilip