如何进行多级Dicitonary数组的递归解析

时间:2015-06-26 07:05:18

标签: ios objective-c

我在JSON响应中对数组的嵌套字典有共同的价值。

我希望在级别方面实现它,以便所有递归都在循环内完成。

代码 - >

·H

@interface MyCategory : NSObject
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *categoryId;
@property (nonatomic, strong) NSString *catIconLeft;
@property (nonatomic, strong) NSString *catIconRight;
@property (nonatomic, strong) NSString *parentId;
@property (nonatomic, strong) NSArray  *categories;

- (id)initWithRootDictionary:(NSDictionary *)dictionary;
@end

的.m ------->

 @implementation
 - (id)initWithRootDictionary:(NSDictionary *)dictionary
{
self = [super init];
self.type = dictionary[@"type"];
self.name = dictionary[@"name"];
self.categoryId = dictionary[@"categoryId"];
self.catIconLeft = dictionary[@"catIconLeft"];
self.catIconRight = dictionary[@"catIconRight"];
self.parentId = dictionary[@"parentId"];
if (dictionary[@"category"]) {
    NSMutableArray *categories = [NSMutableArray new];
    for (NSDictionary *cat in dictionary[@"category"]) {
        MyCategory *category = [[MyCategory alloc] initWithRootDictionary:cat];
        [categories addObject:category];
    }
    self.categories = categories;
 }

 return self;
 }
 @end

查看控制器调用 - >

-(void)call_CategoryListData
{ 
//...
NSMutableDictionary * responseDic = [results objectForKey:@"RESPONSE"];
NSMutableArray *      catArray    = [responseDic objectForKey:@"Category"];

NSMutableArray *result = [NSMutableArray new];
for (NSDictionary *categoryDic in catArray) {
    MyCategory *category = [[MyCategory alloc] initWithRootDictionary:categoryDic];
    [result addObject:category];
}

}

结果数组再次包含嵌套级别的字典和数组。  我想以这种方式解析dict数组,所有主类和子类以及子类都应该属于相应的对象。

例如

  • 电子           - >手机配件 - >耳机,充电器,电池等......           ----------所以----------

我的JSON LINK

1 个答案:

答案 0 :(得分:1)

很难理解,你想要什么,但我会尝试回答

你的递归方法将获得一些字典,创建其中描述的对象,并使用子字典调用自身,如果传入的字典是类别

- (NSArray *) mapCategories:(NSArray*) categoriesDictArray {
    NSMutableArray *result = [NSMutableArray array];
    for(NSDictionary *objectDict in categoriesDictArray) {
        MyCategory *category = [MyCategory categoryWithDictionary:objectDict];
        [result addObject:category];
        if(objectDict[@"Category"]) {
           category. categories = [self mapCategories:objectDict[@"Category"]];    
        }
    }

    return result;
}

//place, where you get your first call
NSArray *mappedCategories = [self mapCategories:result[@"RESPONSE"][@"Category"] ];

希望你明白这个想法