Restkit 对象映射在映射过程中遇到错误
Posted
技术标签:
【中文标题】Restkit 对象映射在映射过程中遇到错误【英文标题】:Restkit object mapping encountered errors during mapping 【发布时间】:2012-09-04 07:56:30 【问题描述】:我正在使用带有对象映射的 Restkit,但我似乎收到了一条错误消息:Encountered errors during mapping: Expected an object mapping for class of type 'Rating', provider returned one for 'Error'
- 现在我已经为 Rating 和 Error 对象设置了映射和序列化,所以我不明白为什么会混淆。有人可以帮忙吗?
这是从类返回的映射
// Rating class
+ (RKObjectMapping *)getRestKitObjectMapping
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Rating class]];
[mapping mapAttributes:@"id", @"mics", @"mdate", @"ipaddress", nil];
[mapping mapKeyPath:@"user_id" toAttribute:@"userID"];
[mapping mapKeyPath:@"fid" toAttribute:@"fid"];
return mapping;
// Error class
+ (RKObjectMapping *)getRestKitObjectMapping
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Error class]];
[mapping mapKeyPath:@"code" toAttribute:@"code"];
[mapping mapKeyPath:@"message" toAttribute:@"message"];
return mapping;
这是对象路由
[[RKObjectManager sharedManager].router routeClass:[Rating class] toResourcePath:@"/mic/:id"];
[[RKObjectManager sharedManager].router routeClass:[Rating class] toResourcePath:@"/mic" forMethod:RKRequestMethodPOST];
[[RKObjectManager sharedManager].mappingProvider setMapping:[Rating getRestKitObjectMapping] forKeyPath:@"ratings"];
[[RKObjectManager sharedManager].mappingProvider setMapping:[Error getRestKitObjectMapping] forKeyPath:@"error"];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[[Rating getRestKitObjectMapping] inverseMapping] forClass:[Rating class]];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[[Error getRestKitObjectMapping] inverseMapping] forClass:[Error class]];
Rating *rating = [[Rating alloc] init];
[[RKObjectManager sharedManager] postObject:rating delegate:self];
这些是委托方法,didLoadObjects
确实被调用了
- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error
NSLog(@"Object loading failed with error: %@ ----- body: %@", error.localizedDescription, objectLoader.response.bodyAsString);
- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects
NSLog(@"Objects received: %@", objects);
NSLog(@"Respond body: %@", objectLoader.response.bodyAsString);
这是 JSON 响应
"error":"error":1,"code":342,"message":"You have already rated this one"
另外,当我查看我的 REST php 后端上的 $_POST 值时,它实际上是空的,这意味着它没有接收到发布对象...这是为什么呢?我的路由好像没问题?
【问题讨论】:
【参考方案1】:您对后端服务有任何控制权吗?
如果是这样,我会更改您发回数据的方式。当您进行“postObject”调用时,唯一预期的响应是“Rating”。我知道您设置了一个“错误”映射,但由于您发布的对象是一个“评级”对象,它期待它回来。
这里更合适的做法是让服务将 HTTP 状态代码更改为 403(禁止),或者不是 200(正常)。然后你可以在“objectLoader:didFailWithError:”委托方法中处理错误。
【讨论】:
我确实可以控制后端,但是如果我提供 HTTP 状态代码 403,我仍然能够提供 JSON 数据吗?以上是关于Restkit 对象映射在映射过程中遇到错误的主要内容,如果未能解决你的问题,请参考以下文章
RestKit 映射错误“无法将对象集合映射到非可变集合。”