我有一个实体类数组(例如SubmittedAnswer)。它的JSON格式如下所示。
{
"submittedAnswers": [{
"submittedQuestionId": "C7B3C4BE-CC3C-438F-A118-E798884A5FE0",
"serialNumber": 4,
"option": " it has a very large mass.",
"testQuestionId": "55230160-b905-47d5-a91c-e1dda6dd0634",
}, {
"submittedQuestionId": "9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0",
"serialNumber": 1,
"option": " downward",
"testQuestionId": "fd0b3ae0-e999-48a6-89b8-a89b02e7b793",
}]
}
我想从该数组中找到“ 选项 ”字段,其中“ submittedQuestionId ”是“某事。 ...“。我不想用于循环。 目前我正在使用以下代码。
NSString *submittedQuestionId = "something...."
int index = [[submittedAnswers valueForKey:@"submittedQuestionId"] indexOfObject:submittedQuestionId];
NSString *option = [[submittedAnswers valueForKey:@"option"] objectAtIndex:index];
我需要更好地解决这个问题。
答案 0 :(得分:3)
假设submittedAnswers
是NSDictionary对象的NSArray,我在这里找到答案:
Stack Overflow > iPhone - Searching NSArray of NSDictionary objects
// Array `submittedAnswers` of sample data
NSArray* submittedAnswers = @[
@{
@"submittedQuestionId" : @"C7B3C4BE-CC3C-438F-A118-E798884A5FE0" ,
@"serialNumber" : @4 ,
@"option" : @" it has a very large mass." ,
@"testQuestionId" : @"55230160-b905-47d5-a91c-e1dda6dd0634" } ,
@{
@"submittedQuestionId" : @"9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0" ,
@"serialNumber" : @1 ,
@"option" : @" downward" ,
@"testQuestionId" : @"fd0b3ae0-e999-48a6-89b8-a89b02e7b793" } ] ;
NSString *submittedQuestionId = @"9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0" ;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"submittedQuestionId = %@", submittedQuestionId] ;
NSArray* foundQuestions = [submittedAnswers filteredArrayUsingPredicate:predicate] ;
NSDictionary* foundQuestion = foundQuestions[0] ;
答案 1 :(得分:2)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"submittedQuestionId == %@", yourSubmittedQuestionId];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
id firstFoundObject = nil;
if ([filteredArray count] > 0) {
firstFoundObject = [filteredArray objectAtIndex:0];
}
请确保您的SubmittedAnswer
班级有财产submittedQuestionId