展平嵌套的NSDictionary

时间:2013-05-11 03:58:41

标签: objective-c nested nsdictionary

是否有可能“扁平化”NSDictionary?我检索JSON数据,并用它填充字典。最终看起来像这样:

data: {
    author = "user"
    message = "message"
        response: {
             author = "user2"
             message = "message2"
                 response2: {
                     author = "user"
                     message = "message3"

每个响应的级别数量会有所不同。我完全不知道如何使用这些数据。正常的路线是

NSString *author = [[messages objectForKey:@"data"] objectForKey:@"author"];

但是因为我不知道字典会有多深,所以这不起作用。有没有人知道处理这个的方法?

1 个答案:

答案 0 :(得分:2)

这是在保持对父消息的引用的同时展平字典的一种方法。

@interface NSDictionary(Flatten)
- (NSArray*) flattenWithParent:(id)parent;
- (NSArray*) flatten;
@end

@implementation NSDictionary(Flatten)
- (NSArray*) flattenWithParent:(id)parent
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSMutableArray      *flat = [NSMutableArray arrayWithObject:dict];

    if (parent != nil)
        dict[@"parent"] = parent;

    [self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        if ([value isKindOfClass:[NSDictionary class]])
            [flat addObjectsFromArray:[value flattenWithParent:dict]];
        else
            [dict setObject:value forKey:key];
    }];

    return flat;
}

- (NSArray*) flatten
{
    return [self flattenWithParent:nil];
}

@end


int main (int argc, const char * argv[])
{
    @autoreleasepool {

        NSDictionary *data = @{
           @"author": @"user",
           @"message":@"message",
           @"response": @{
                   @"author": @"user2",
                   @"message":@"message2",
                   @"response": @{
                           @"author": @"user",
                           @"message":@"message3"
                   }
               }
           };

        NSArray *messages = [data flatten];
        NSLog(@"Message count = %lu", messages.count);
        NSLog(@"%@",messages);
    }
    return 0;
}

我得到以下(重新格式化)输出:

2013-05-11 09:37:31.293 Dummy[22896:303] Message count = 3
2013-05-11 09:37:31.295 Dummy[22896:303] (
{
    author = user;
    message = message;
},
{
    author = user2;
    message = message2;
    parent =         {
        author = user;
        message = message;
    };
},
{
    author = user;
    message = message3;
    parent =         {
        author = user2;
        message = message2;
        parent =             {
            author = user;
            message = message;
        };
    };
})