我做了非常类似的事情,而且效果很好。我知道你的问题是关于为什么RKObjectSerializer不按照你的期望工作,但也许是你设置中的其他问题。我发布我的代码以提供一个能够正常运行的干净示例。话虽如此,在阅读RKObjectSerializer文档后,我没有看出为什么你不能像在我的示例中直接设置一样初始化RKParams。
路由器设置:RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:kApiUrlBase]
[objectManager.router routeClass:[PAPetPhoto class] toResourcePath:@"/pet/uploadPhoto" forMethod:RKRequestMethodPOST]
映射设置:
RKObjectMapping *papetPhotoMapping = [RKObjectMapping mappingForClass:[PAPetPhoto class]];
[papetPhotoMapping mapKeyPath:@"id" toAttribute:@"identifier"];
[papetPhotoMapping mapAttributes:@"accountId", @"petId", @"photoId", @"filename", @"contentType", nil];
[objectManager.mappingProvider addObjectMapping:papetPhotoMapping];
[objectManager.mappingProvider setSerializationMapping:[papetPhotoMapping inverseMapping] forClass:[PAPetPhoto class]];
[objectManager.mappingProvider setMapping:papetPhotoMapping forKeyPath:@"petPhoto"];
这篇文章的内容:(注意,由于我在块中构建了所有参数,因此我的对象只是一个虚拟实例,以触发正确的路由和映射器。)
PAPetPhoto *photo = [[PAPetPhoto alloc] init];
[[RKObjectManager sharedManager] postObject:photo delegate:self block:^(RKObjectLoader *loader){
RKParams* params = [RKParams params];
[params setValue:pet.accountId forParam:@"accountId"];
[params setValue:pet.identifier forParam:@"petId"];
[params setValue:_photoId forParam:@"photoId"];
[params setValue:_isThumb ? @"THUMB" : @"FULL" forParam:@"photoSize"];
[params setData:data MIMEType:@"image/png" forParam:@"image"];
loader.params = params;
}];
服务端终端点(Java,Spring MVC)
@RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> handleFormUpload(@RequestParam("accountId") String accountId,
@RequestParam("petId") String petId,
@RequestParam("photoId") String photoId,
@RequestParam("photoSize") PhotoSizeEnum photoSize,
@RequestParam("image") Part image) throws IOException {
if (log.isTraceEnabled())
log.trace("uploadPhoto. accountId=" + accountId + " petId=" + petId + " photoId=" + photoId + " photoSize=" + photoSize);
PetPhoto petPhoto = petDao.savePetPhoto(accountId, petId, photoId, photoSize, image);
Map<String, Object> map = GsonUtils.wrapWithKeypath(petPhoto, "petPhoto");
return map;
}
服务器响应JSON(请注意"petPhoto"的keyPath对应于映射设置):
{
petPhoto = {
accountId = 4ebee3469ae2d8adf983c561;
contentType = "image/png";
filename = "4ebee3469ae2d8adf983c561_4ec0983d036463d900841f09_3FED4959-1042-4D8B-91A8-76AA873851A3";
id = 4ee2e80203646ecd096d5201;
petId = 4ec0983d036463d900841f09;
photoId = "3FED4959-1042-4D8B-91A8-76AA873851A3";
};
}
委托:
- (void) objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {
if ([objectLoader wasSentToResourcePath:@"/pet/uploadPhoto"]) {
PAPetPhoto *photo = (PAPetPhoto*)object;
}
}