1

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

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

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

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

但由于我不知道字典的深度,所以这行不通。有谁知道处理这个的方法?

4

1 回答 1

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;
        };
    };
})
于 2013-05-11T07:40:18.987 回答