Iphone NSDictionary扁平化层次结构
我有一个NSDictionary对象,如下所示:Iphone NSDictionary扁平化层次结构,iphone,objective-c,ios,xcode,ipad,Iphone,Objective C,Ios,Xcode,Ipad,我有一个NSDictionary对象,如下所示: dictionary: { data = { "access_token" = "xxx"; "expires_in" = 00; "refresh_token" = "yyy"; "token_type" = bearer; }; } dictionary: { "access_token" = "xxx"; "expir
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;
};
如何将其展平以便删除“数据”对象?有没有快速的方法?
因此,输出应如下所示:
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;
};
在您的示例中,扁平dict:
//grab data
NSDictionary *data = [yourDict objectForKey:@"data"];
assert(data != nil);
NSDictionary *flatDict = data; //OR data.copy // OR [NSDictionary dictionaryWithDictionary:data];
“数据”看起来不像是一本词典。试一试
id what = [dict objectForKey : @"data"];
NSLog(@"%@", [what class]);
它说什么?使用递归函数,该方法唯一的问题是,如果嵌套字典中的键恰好相同,它将替换旧数据
- (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];
}
顺便问一下,我希望访问令牌数据无效。字典和数据的密钥是什么?您不觉得字典的格式错误吗
NSDictionary*result=[dictionary objectForKey:@“data”]代码>不起作用。。。。我收到***由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:***-[\u NSPlaceholderDictionary initWithObjects:forKeys:count:]:尝试从对象[0]插入零对象'***第一次抛出调用堆栈:这不会导致扁平化dictionary@Imme22009那么你没有给出你的字典的确切内容正如我说的,这不会使它变平。这将产生一个dict,其中包含一个具有dataDict@Daij-詹:现在好了吗。。你不认为他有错误的目标吗。。在字典里你有key:value
而不是key=value
@inderkumarratore是的,我知道。我不确定他是否想要一份复印件或其他什么:我编辑了我的答案