如何在RestKit中手动进行对象映射?

时间:2012-10-03 11:54:33

标签: restkit

我在客户端和服务器端都有一个响应对象,如下所示:

客户方:

//BaseResponse.h
@interface BaseResponse : NSObject{
    NSString *code;
    NSString *message;
    NSObject *responseObject;
}
+(RKObjectMapping *)objectMapping;

//BaseResponse.m
+(RKObjectMapping *)objectMapping{
    RKObjectMapping *baseResponseMapping = [RKObjectMapping mappingForClass:[BaseResponse class]];
    [baseResponseMapping mapKeyPath:@"code" toAttribute:@"code"];
    [baseResponseMapping mapKeyPath:@"message" toAttribute:@"message"];
    [baseResponseMapping mapKeyPath:@"responseObject" toAttribute:@"responseObject"];

    return baseResponseMapping;
}

服务器端:

public class BaseResponse {
   private String code; 
   private String message;  
   private Object responseObject;
...
}

当我从ios调用restful web服务时,它返回一个BaseResponse对象。但是BaseResponse中的responseObject可以根据Web服务方法而变化。所以我在服务器端和客户端做了Object。

所以我的问题是:在调用- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response方法或- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects方法之后,如何在restkit中手动进行对象映射。

提前致谢。

2 个答案:

答案 0 :(得分:0)

RESTkit实际上对此有很好的支持。基本上,您需要在响应中包含一些内容,以确定您希望执行哪种映射。

为此,您将映射定义为动态映射,然后从那里开始。

我可以从维基中复制这个例子,但那会是作弊,所以我建议你看看this part of the mapping explanation

答案 1 :(得分:0)

我的解决方案就是这个

...
[objectManager postObject:nil path:path parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
    BaseResponse *response = (BaseResponse *)[[result array] objectAtIndex:0];
    NSError *error = nil;
    AppVersion *appVersion = [[AppVersion alloc]init];
    RKMappingOperation *operation = [[RKMappingOperation alloc]
                                                 initWithSourceObject:response.responseObject destinationObject:appVersion mapping:[AppVersion objectMapping] ];

    BOOL success = [operation performMapping:&error];
...