0

我有一个像这样的 NSDictionary 对象:

dictionary: {
    data =     {
        "access_token" = "xxx";
        "expires_in" = 00;
        "refresh_token" = "yyy";
        "token_type" = bearer;
    };
}

如何展平它以便删除“数据”对象?有没有快速的方法来做到这一点?所以输出应该是这样的:

dictionary: {

        "access_token" = "xxx";
        "expires_in" = 00;
        "refresh_token" = "yyy";
        "token_type" = bearer;
};
4

4 回答 4

1
NSDictionary *dataDict = [mainDict  objectForKey:@"data"];
于 2012-12-08T17:28:31.037 回答
0

您的示例中的平面字典:

//grab data
NSDictionary *data = [yourDict objectForKey:@"data"];
assert(data != nil);
NSDictionary *flatDict = data; //OR data.copy // OR [NSDictionary dictionaryWithDictionary:data];
于 2012-12-08T17:45:05.707 回答
0

它看起来不像“数据”是一个 NSDictionary。尝试

id what = [dict objectForKey : @"data"];
NSLog(@"%@", [what class]); 

它说什么?

于 2012-12-08T19:09:52.667 回答
0

使用递归函数,这种方法的唯一问题是如果嵌套字典中的键碰巧相同,它将替换旧数据

- (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];
}
于 2014-07-31T11:15:07.023 回答