2015-09-06 70 views
0

我正在使用RestKIT为我想要使用的API发出GET请求。可悲的是没有输出。这是GET请求的输出:Objective-C RestKit no输出

{ 
    "return_code": 0, 
    "return_message": "", 
    "result": { 
    "products_count": 2, 
    "product": [ 
     { 
     "id": "2440508995", 
     "name": "Long Sweater", 
     "description": "This product guarantees warmth in times of need.", 
     "price": 8, 
     "categories_ids": "73978179" 
     }, 
     { 
     "id": "2455113539", 
     "name": "Tommy Hilfiger Pants", 
     "description": "Exclusive brown pants", 
     "price": 13, 
     "categories_ids": "" 
     } 
    ] 
    } 
} 

很显然,我只想得到一个数组,其中所有的产品都存储。这是我的方法来做到这一点。

- (void)loadProducts 
{ 
    RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[Result class]]; 
    [resultMapping addAttributeMappingsFromDictionary:@{ 
                  @"products_count": @"products_count", 

                  }]; 

    RKObjectMapping* productMapping = [RKObjectMapping mappingForClass:[Product class]]; 
    [productMapping addAttributeMappingsFromDictionary:@{ 
                 @"id": @"id", 
                 @"name": @"name", 
                 @"description": @"description", 
                 @"price": @"price", 
                 @"categories_ids": @"categories_ids" 
                 }]; 

    [resultMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"product" toKeyPath:@"product" withMapping:productMapping]]; 



    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"result" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; 

    NSURL *URL = [NSURL URLWithString:@"https://api.api2cart.com/v1.0/product.list.json?api_key=//some keyf&store_key=//some key"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
    RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[ responseDescriptor ]]; 
    [objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 

     RKLogInfo(@"Load collection of Products: %@", mappingResult.array); 
    } failure:^(RKObjectRequestOperation *operation, NSError *error) { 
     RKLogError(@"Operation failed with error: %@", error); 
    }]; 

    [objectRequestOperation start]; 

} 

我做了两个班,一个是具有NSNumber的“products_count”,并与所有的产品态度,一个产品类的结果。问题是即使建立了连接并且没有“错误”,mappingResult.array显然是空的。代码中的错误是什么?

+0

您正在结果响应描述符中使用产品映射... – Wain

+0

所以我用resultMapping替代它? –

+0

这将是第一件要做的事情。你真的需要结果容器吗?您可以直接向下钻取具有响应描述符键路径的产品... – Wain

回答

1

你实际上并不需要你的Result类,因为数组已经给你了账号,你可以直接进入数组。

因此,您最初的问题是您在响应描述符中使用了错误的映射。您只需切换到结果映射。

您可以在响应描述符中使用产品映射,但应将关键路径更改为result.products

你的产品的映射也有一个问题,因为description是现有的方法在所有子类NSObject,所以你需要通过添加一个名为像overviewtitle属性来更改它的用法。