使用 Restkit 将对象发送回服务器时,仅当我附加图像时,我才遇到子对象嵌套数组的问题。
这是我用于所有请求的映射摘要:
// mapping for post tag details
tagMapping = [RKObjectMapping mappingForClass:[TagObject class]];
[tagMapping mapKeyPath:@"id" toAttribute:@"tagId"];
[tagMapping mapKeyPath:@"name" toAttribute:@"tagName"];
[[RKObjectManager sharedManager].mappingProvider setMapping:tagMapping forKeyPath:@"tags"];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[tagMapping inverseMapping] forClass:[TagObject class]];
// mapping for posts
poastMapping = [[RKObjectMapping alloc] init];
poastMapping = [RKObjectMapping mappingForClass:[PoastObject class]];
[poastMapping mapKeyPath:@"id" toAttribute:@"poastId"];
[poastMapping mapKeyPath:@"user_id" toAttribute:@"userId"];
[poastMapping mapKeyPath:@"blurb" toAttribute:@"blurb"];
[poastMapping mapKeyPath:@"photo" toAttribute:@"photo"];
[poastMapping mapKeyPath:@"avatar" toAttribute:@"avatar"];
[poastMapping mapKeyPath:@"date_created" toAttribute:@"dateCreated"];
[poastMapping mapKeyPath:@"firstname" toAttribute:@"firstName"];
[poastMapping mapKeyPath:@"lastname" toAttribute:@"lastName"];
[poastMapping mapKeyPath:@"session" toAttribute:@"session"];
[poastMapping mapKeyPath:@"device" toAttribute:@"device"];
[poastMapping mapKeyPath:@"comments" toAttribute:@"iComments"];
[poastMapping mapKeyPath:@"commentcount" toAttribute:@"commentCount"];
[poastMapping mapKeyPath:@"pointcount" toAttribute:@"pointCount"];
[poastMapping mapKeyPath:@"heartcount" toAttribute:@"heartCount"];
[poastMapping mapKeyPath:@"postcount" toAttribute:@"postCount"];
[poastMapping mapKeyPath:@"hearted" toAttribute:@"hearted"];
[poastMapping mapKeyPath:@"total" toAttribute:@"total"];
[poastMapping mapKeyPath:@"tags" toRelationship:@"tags" withMapping:tagMapping];
[[RKObjectManager sharedManager].mappingProvider addObjectMapping:poastMapping];
[[RKObjectManager sharedManager].mappingProvider setMapping:poastMapping forKeyPath:@"posts"];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[poastMapping inverseMapping] forClass:[PoastObject class]];
这是发送请求的块(请注意,某些更改仅在附加图像时发生)
[[RKObjectManager sharedManager] sendObject:obj toResourcePath:@"/posts/submit" usingBlock:^(RKObjectLoader *loader) {
loader.targetObject = nil;
loader.delegate = self;
loader.method = RKRequestMethodPOST;
if([obj image]){
RKObjectMapping* serializationMapping = [[[RKObjectManager sharedManager] mappingProvider] serializationMappingForClass:[PoastObject class]];
NSError* error = nil;
NSDictionary* dictionary = [[RKObjectSerializer serializerWithObject:obj mapping:serializationMapping] serializedObject:&error];
RKParams* params = [RKParams paramsWithDictionary:dictionary];
NSData* imageData = UIImagePNGRepresentation([obj image]);
[params setData:imageData MIMEType:@"image/png" forParam:@"image"];
loader.params = params;
}
}];
当发送没有图像的请求时,'tags' 数组按预期以 'array' 类型到达 PHP。但是,当发送带有图像的请求时,标签数组以“字符串”类型出现,如下所示:
({ id = 2;name = Science;},{ id = 4;name = Academics;})