我在当前项目中使用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类?
谢谢并道歉我的问题中的任何遗漏或错误。