Reputation: 4129
I've got an NSDictionary object like this:
dictionary: {
data = {
"access_token" = "xxx";
"expires_in" = 00;
"refresh_token" = "yyy";
"token_type" = bearer;
};
}
How can I flatten it so that I remove the 'data' object? Is there a quick way to do that? So the output should look like this:
dictionary: {
"access_token" = "xxx";
"expires_in" = 00;
"refresh_token" = "yyy";
"token_type" = bearer;
};
Upvotes: 0
Views: 625
Reputation: 959
using recursive function, the only problem with this method is it will replace the old data if key happened to be the same in the nested dictionary
- (NSDictionary *)flattedDictionary{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *key in self.allKeys) {
id object = [self objectForKey:key];
if (![object isKindOfClass:[NSDictionary class]] && !isNull(object)) {
[dict setObject:object
forKey:key];
} else if ([object isKindOfClass:[NSDictionary class]]){
[dict addEntriesFromDictionary:[object flattedDictionary]];
}
}
return [NSDictionary dictionaryWithDictionary:dict];
}
Upvotes: 0
Reputation: 2057
It doesn't look like "data" is an NSDictionary. Try
id what = [dict objectForKey : @"data"];
NSLog(@"%@", [what class]);
What does it say?
Upvotes: 0
Reputation: 39988
NSDictionary *dataDict = [mainDict objectForKey:@"data"];
Upvotes: 1
Reputation: 50109
flat dict in your example:
//grab data
NSDictionary *data = [yourDict objectForKey:@"data"];
assert(data != nil);
NSDictionary *flatDict = data; //OR data.copy // OR [NSDictionary dictionaryWithDictionary:data];
Upvotes: 0