【发布时间】:2015-01-09 01:40:56
【问题描述】:
我在当前项目中使用 RestKit 来促进与定制 REST API 的通信。我在从索引端点检索资源集合时遇到问题。我能够检索资源,但无法将它们映射到目标类。
以下是详细信息(我已将小部件替换为有问题的实际业务对象)。
端点是 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");
}];
我的 [Widget mapping] 方法如下所示:
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,得到了 Widget(见 [RKObjectMapping requestMapping])
我在这里做错了什么?我应该如何正确配置我的请求以将每个返回的对象映射到 Widget 类?
对于我的问题中的任何遗漏或错误,我们深表歉意。
【问题讨论】:
标签: ios objective-c restkit restkit-0.20