在NSMutableArray中过滤JSON项目
我有一个小问题,我有一个json提要,我想在数组中显示其国家=法国的项目怎么办?谢谢
(Objective-C的)
我的JSON:
在NSMutableArray中过滤JSON项目
{
"menu": "Fichier",
"commandes": [
{
"country": "France",
"city": "Paris"
},
{
"country": "USA",
"city": "New York"
},
{
"country": "Canada",
"city": "Quebec"
}
]
}
你需要使用解析您的JSON数据NSPredicate
来搜索数组中的数据
使用
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"country == %@", @"France"];
NSArray *filteredArray = [[arr objectForKey:@"commandes"] filteredArrayUsingPredicate:predicate];
当我通过“Fra”并获得“France”对象时,是否可以获取数组? –
不,这个谓词不适用于这种查询。你需要寻找包含谓词的种类。 –
好的,谢谢。 –
这将帮助:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"commandes" ascending:TRUE];
[sourceArr sortUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
首先使用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);
如果您已经创建了数组,并且只想添加使用NSPredicate的过滤器,则此代码仅从实际Json获取法国数组。 – Dilip
请检查这个环节,我希望它有助于[过滤的NSMutableArray(http://stackoverflow.com/questions/110332/filtering-nsarray-into-a-new-nsarray- in-objective-c) –