您认为两个映射是答案是正确的。假设您使用的是最新版本的 RestKit,类似以下的内容将起作用。
还要记住,为了真正利用 RestKit 提供的功能,JSON 必须符合键值编码。例如,在此示例中,JSON 包装在“响应”键中。
我刚刚从我正在处理的项目中提取了这个并更改了所有名称。这应该让你走上正确的道路。
RKObjectMapping *postObjectMapping = [RKObjectMapping requestMapping];
[postObjectMapping addAttributeMappingsFromDictionary:@{
@"param1" : @"param1",
@"param2" : @"param2"}];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:postObjectMapping objectClass:[PostObjectModel class] rootKeyPath:nil];
RKObjectMapping *returnedObjectMapping = [RKObjectMapping mappingForClass:[ReturnedModel class]];
[returnedObjectMapping addAttributeMappingsFromDictionary:@{
@"returnedParam1" : @"returnedParam1",
@"returnedParam2": @"returnedParam2",
@"returnedParam3": @"returnedParam3"}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:returnedObjectMapping pathPattern:nil keyPath:@"Response" statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"error" toKeyPath:@"errorMessage"]];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError);
RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping pathPattern:nil keyPath:@"errors" statusCodes:statusCodes];
PostModel *objectToBePosted = [PostModel new];
[login setParam1:something];
[login setParam2:something];
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://BASEURLHERE"]];
[objectManager addRequestDescriptor:requestDescriptor];
[objectManager addResponseDescriptor:responseDescriptor];
[objectManager addResponseDescriptor:errorDescriptor];
NSMutableURLRequest *request = [objectManager requestWithObject:objectToBePosted method:RKRequestMethodPOST path:@"/REST/OF/PATH/GOES/HERE" parameters:nil];
RKObjectRequestOperation *operation = [objectManager objectRequestOperationWithRequest:request
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(@"Success block: %@", mappingResult);
} failure: ^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"Failed with error: %@", [error localizedDescription]);
}];
[objectManager enqueueObjectRequestOperation:operation];
}