Objective C - NSDictionary 解析嵌套 JSON

Objective C - NSDictionary parsing nested JSON

这是一个深度嵌套的 JSON,我正在尝试将其解析并创建到模型对象中。

基本上我需要创建模型对象,直到 'Child' 数组有 0 个元素。

这就是我正在做的事情

        dictTree = [dict[@"jsonTree"] mutableCopy];
        NSMutableArray *children = [[NSMutableArray alloc] init];
        if (dictTree.count > 0)
        {
            while (true)
            {
                CategoryChild *categoryChild = [[CategoryChild alloc]init];
                NSString *str = dictTree[@"id"];
                categoryChild.childId = str;
                categoryChild.name = dictTree[@"name"];
                categoryChild.type = dictTree[@"type"];
                categoryChild.parent = dictTree[@"parent"];
                categoryChild.symbol = dictTree[@"symbol"];
                categoryChild.multiple = dictTree[@"multiple"];
                categoryChild.metricUnit = dictTree[@"metricUnit"];

                [children addObject:categoryChild];
                dictTree = [dictTree[@"child"] mutableCopy];

                if (dictTree.count == 0)
                {
                    break;
                }
            }

            categoryItem.children = children;
            [categoryList addObject:categoryItem];
        }

不幸的是,在第二次迭代期间,当我访问 dictTree[@"id"] - 崩溃

'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance

问题似乎是我正在将字典分配给 'child' 字典并且它似乎喜欢它。

虽然在调试器中,我可以看到子值。

任何关于如何处理事情或做错了什么的想法都将不胜感激。谢谢。

改变

dictTree = [dict[@"jsonTree"] mutableCopy];

 dictTree = [dict[@"jsonTree"][@"child"] mutableCopy];

这应该可以完成工作。

键 jsonTree 的值是 jSON,而不是您期望的 JSONArrayJSONArray 是 "jsonTree" 中键 "child" 的值。

我希望您知道如果第二个子对象出现在 JSON 数组中,您的代码将无法解析它。查看您的 jSON 每个子键代码只有一个 JSON 看起来不错。但是如果每个键 "child" 有多个 jSON 你需要一个更好的代码来解析。

编辑:

我能想到的更简洁的方法

- (void) parseChildrenArray : (NSArray *) dict {
    for(NSDictionary *child in dict) {
        CategoryChild *createdChild = [self createCategory:child];
        [self.childrenArray addObject:createdChild];
        if ([child[@"child"] count] > 0) {
            [self parseChildrenArray:child[@"child"]];
        }
    }
}

-(CategoryChild *)createCategory: (NSDictionary *)child {
    CategoryChild *ch = [[CategoryChild alloc] init];
    ch.id = child[@"id"];
    //parse other property
    return ch;
}

声明一个 属性

@property (nonatomic,strong) NSMutableArray *childrenArray;

终于打电话

NSDictionary *tree = json[@"jsonTree"];
self.childrenArray = [[NSMutableArray alloc] init];
[self parseChildrenArray:tree[@"child"]];

您的 children 似乎由充满一本字典的数组组成。您需要访问此数组的第一个 object 才能获取字典。

[children addObject:categoryChild];
if ([dictTree[@"child"] count] > 0) {
    dictTree = [dictTree[@"child"][0] mutableCopy];
}

调试器还显示 dictTree 由键 0 处的一个元素组成。该元素就是您的字典。