Reputation: 337
I'm reading a JSON code such as:
[{"question_id":"1",
"trigger_value":"Yes",
"question_text":"What is your first name?",
"question_type":"YN"},
{"question_id":"2",
"trigger_value":"Yes",
"question_text":"What is your second name?",
"question_type":"YN"}
]
But once it's set into NSMutableArray, the duplicate values are deleted. I would like to allow them to check the question_type for each question.
NSString *question_id;
NSString *question_text;
NSString *question_type;
while (dicjson = (NSDictionary*)[enumerator nextObject]) {
question_id = [dicjson objectForKey:@"question_id"];
question_type = [dicjson objectForKey:@"question_type"];
[mutjson setObject:question_id forKey:question_type];
}
Would you give me any idea of allowing duplicate values...? Thanks in advance.
Upvotes: 1
Views: 541
Reputation: 3103
You are confusing an array for a dictionary. An array can hold duplicate values. A dictionary cannot hold duplicate keys.
The JSON response is an array of dictionaries. The way you've written your code, specifically [mutjson setObject:question_id forKey:question_type];
seems to suggest that you are simply using a dictionary.
If you would like to check the question type for each question, try instead:
NSString *question_type;
for (NSMutableDictionary *dict in dicjson) {
// I would suggest renaming dicjson to something more descriptive, like results
question_type = [dict objectForKey: @"question_type"];
// Do what you would like now that you know the type
}
Upvotes: 1
Reputation: 9324
You cannot setObject:forKey:
in NSMutableArray. You have to use addObject:
. Its also much easier to create the array like this:
NSArray *values = [jsonDict allValues];
Upvotes: 1
Reputation: 14667
mutjson looks like a mutable dictionary and not a mutable Array.
So yes, in a dictionary object if you are setting the same key, it will overwrite the previous value. If you need to store dictionary object, create a mutable array and add each object inside that array as a dintionary object...
NSMutableArray *results = [[NSMutableArray alloc] init];
while (dicjson = (NSDictionary*)[enumerator nextObject]) {
question_id = [dicjson objectForKey:@"question_id"];
question_type = [dicjson objectForKey:@"question_type"];
[result addObject:[NSDictionary dictionaryWithObject:question_id forKey:question_type]];
}
Upvotes: 3