来自服务器的 Restkit json 错误响应消息
我花了很多时间来解决这个问题.我使用带有对象映射 2.0 的 Restkit 0.9.3.所有数据都在 JSON 中.我可以正确地进行 GET、POST、PUT 和 DELETE 操作,这是我没有正确捕获和映射的响应主体..
I have used many hours on how to solve this issue. Im using Restkit 0.9.3 with Object Mapping 2.0. All data is in JSON. I can make GET, POST, PUT and DELETE operations correctly, it's the response body I dont catch and map corretly..
所以我的问题是我的restful api 在出现问题时返回错误.我想用restkit映射这些错误,返回这个错误:
So my problem is that my restful api is returning errors when something goes wrong. I want to map those errors with restkit, fx this error is returned:
{代码":401","message": "未经授权"}
我如何正确地映射这个 json?我已经尝试了很多东西并且可以使用一些指导性 - 或者请举一个例子.
How do I map this json correct? I have tried lots of things and could use some guideness - or please give an example of this.
对于 0.10.0 版本,此响应错误可以映射如下:
For version 0.10.0 this response error can be mapped as follows:
RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
[errorMapping mapKeyPath:@"message" toAttribute:@"errorMessage"];
[[[RKObjectManager sharedManager] mappingProvider] setErrorMapping:errorMapping];
返回错误的请求将调用以下委托方法:
Requests that return an error will call the following delegate method:
- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
NSArray *errorMessages = [[error userInfo] objectForKey:RKObjectMapperErrorObjectsKey];
RKErrorMessage *errorMessage = [errorMessages objectAtIndex:0]; // First and only object in your case.
NSString *message = [errorMessage errorMessage];
NSInteger code = [[objectLoader response] statusCode];
NSLog(@"ERROR: [%d] %@", code, message); // => ERROR: [401] Unauthorized
}