2015-01-08 21 views
0

我在当前项目中使用RestKit来促进与定制REST API的通信。我遇到了从索引端点检索资源集合的问题。我能够检索资源,但我无法将它们映射到目标类。RestKit - 映射来自索引端点的资源集合

下面是详细信息(我用实际业务对象替代了小部件)。

端点是GET/api/v1/widgets。该JSON从终点返回看起来是这样的:

{"widgets": [ 
    { 
    "widgets": { 
     "name": "whatsit", 
     "material": "wood", 
     "crafted_by": "Hrunkner" 
    } 
    }, 
    { 
    "widgets": { 
     "name": "doodad", 
     "material": "carbon fiber", 
     "crafted_by": "Zaphod" 
    } 
    } 
]} 

我知道,上面的JSON结构的特质相对于每个资源的节点名称,但是这是目前我无法控制。

我使用的WidgetManager类下面的代码执行请求:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 

// apiBaseURL equals @"http://localhost:3000/api/v1/" 
NSURL *apiBaseURL = [NSURL URLWithString:appDelegate.apiBaseURL]; 
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:apiBaseURL]; 

NSString *itemsPath = @"widgets"; 
NSString *keyPath = @"widgets.widgets"; 
NSIndexSet *statusCodeSet = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); 

RKObjectMapping *requestMapping = [[Widget widgetMapping] inverseMapping]; 

RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping: requestMapping 
                       objectClass:[Widget class] 
                       rootKeyPath:keyPath 
                        method:RKRequestMethodGET]; 

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:requestMapping 
                         method:RKRequestMethodGET 
                        pathPattern:nil 
                         keyPath:keyPath 
                        statusCodes:statusCodeSet]; 
[manager addRequestDescriptor: requestDescriptor]; 
[manager addResponseDescriptor:responseDescriptor]; 

[manager getObjectsAtPath:@"widgets" 
       parameters:@{} 
        success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
         [appDelegate setWidgets:[mappingResult array]]; 
        } failure:^(RKObjectRequestOperation *operation, NSError *error) { 
         NSLog(@"FAIL"); 
        }]; 

我的[小工具映射]的方法是这样的:

RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Widget class]]; 
[mapping addAttributeMappingsFromDictionary:@{ 
               @"name": @"name", 
               @"material": @"material", 
               @"crafted_by": @"craftedBy" 
               }]; 
return mapping; 

在我看来,该使用inverseMapping是个问题,但是当我尝试使用[Widget widgetMapping]而不是[[Widget widgetMapping] inverseMapping]作为请求映射时,我得到以下错误

RKRequestDescriptor对象必须使用其 目标类的NSMutableDictionary映射初始化,得到了小工具(见 [RKObjectMapping requestMapping])

什么我错在这里做什么?我应该如何正确配置我的请求来将每个返回的对象映射到Widget类?

谢谢并道歉我的问题中的任何遗漏或错误。

回答

0

事实证明,仅使用响应描述符的逆映射允许对象映射成功进行。以前我试图对请求和响应描述符使用相同的映射,这是行不通的。因此,将请求映射更改为只需[Widget requestmapping],然后将[requestMapping inverseMapping]传递给请求描述符init即可解决我的问题。当然,这将需要重命名局部变量requestMapping,因为它实际上对请求描述符没有用处。

以下问题的答案在澄清请求与响应描述符中映射的功能方面提供了正确方向的推动:https://stackoverflow.com/a/23217042/757806