1

我是 Xcode 的新手,我正在使用 AFNetworking 从服务器获取数据。

我正在尝试使用递归函数从响应中提取以下 JSON 数据:

{
    "id": "12345",
    "version": 1,
    "name": "apple",
    "mainCategory": {
      "id": "23456",
      "version": 2,
      "name": "fruit",
      "mainCategory": {
        "id": "food",
        "version": 1,
        "name": "eat",
        "mainCategory": {
          "id": "root",
          "version": 1,
          "name": "Root",
          "mainCategory": null,
          "productCount": 1,
          "leaf": null,
          "productClass": null,
          "loaded": true
        },
        "productCount": 13,
        "leaf": null,
        "productClass": "xxx",
        "loaded": true
      },
      "productCount": 0,
      "leaf": null,
      "productClass": "xxx",
      "loaded": true
    },
    "productCount": 0,
    "leaf": "1",
    "productClass": "xxx",
    "loaded": true
  }

下面是函数返回对象的递归方法。mainCategory 嵌套在块内

- (ProductCategory *) recursive :(NSDictionary *)productcat
{

    NSDictionary *productcategory = productcat;
    ProductCategory *p = [[ProductCategory alloc] init];
    if (![[productcategory objectForKey:@"mainCategory"]  isEqual: NULL])
    {
        [p setIdentifier:[productcategory objectForKey:@"id"]];
        [p setName:[productcategory objectForKey:@"name"]];
        [p setLeaf:[productcategory objectForKey:@"leaf"]];
        [p setProductClass:[productcategory objectForKey:@"productClass"]];
        [p setProductCount:[productcategory objectForKey:@"productCount"]];
        [p setVersion:[productcategory objectForKey:@"version"]];
        [p setMainCategory:[productcategory objectForKey:@"mainCategory"]];
        NSDictionary *mainCategory = [productcategory objectForKey:@"mainCategory"];
        [self recursive:mainCategory];

    }

    return p;

}

如何提取数据并在达到深度后停止并缩回?

mainCategory 又是 ProductCategory 的一个对象

ProductCategory is NSobject

@interface ProductCategory : NSObject


@property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) NSString *identifier;
@property (nonatomic, strong) ProductCategory *mainCategory;
@property(retain) NSNumber *productCount;
@property (retain) NSNumber *version;

@property (nonatomic, strong) NSString *leaf;
@property (nonatomic, strong) NSString *productClass;
4

1 回答 1

0
 - (ProductCategory *) recursive :(NSDictionary *)productcat
 {
     ProductCategory *p = nil;
     if (productcat != nil) {
        p = [[ProductCategory alloc] init];
        p.identifier = productcat[@"id"];
        p.name = productcat[@"name"];
        p.leaf = productcat[@"leaf"];
        p.productClass = productcat[@"productClass"];
        p.productCount = productcat[@"productCount"];
        p.version = productcat [@"version"];
        p.mainCategory = [self recursive:productcat[@"mainCategory"]];
     }

    return p;
 }
于 2013-11-08T14:48:21.920 回答