使用RestKit v0.21映射原始json响应

时间:2013-10-29 14:28:41

标签: json restkit restkit-0.20

我有一个API,要求我发布一个复杂的JSON对象。 API使用原始ID(或错误对象)保存和响应。我无法映射原始ID。有任何想法吗?为简单起见,下面的示例不是POST对象映射,但我的一些API调用也需要这样做。

我看到了使用RestKit构建请求的建议,并将其传递给AFNetworking,但这不会解析可能的错误返回对象。

RKObjectMapping* map = [RKObjectMapping mappingForClass:[MyPrimitiveResponse class]];
[map addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"success"]];

RKResponseDescriptor *errDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[MyErrorResponse objectMap] method:RKRequestMethodGET  pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassServerError)];

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:map method:RKRequestMethodGET pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

NSURL *URL = [NSURL URLWithString:apiUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[ errDescriptor, responseDescriptor ]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    RKLogInfo(@"Load collection of Articles: %@", mappingResult.array);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    RKLogError(@"Operation failed with error: %@", error);
}];

[objectRequestOperation start];

我在调试器中收到以下错误:

  

2013-10-29 10:23:15.196 TestParser [6988:70b] E app:MyHomeViewController.m:54操作失败,错误:错误Domain = org.restkit.RestKit.ErrorDomain Code = -1017“加载不可处理内容类型为'application / json'的响应(200)“UserInfo = 0x8daca20 {NSErrorFailingURLKey = ....., NSUnderlyingError = 0x8db4cd0”操作无法完成。(Cocoa error 3840。)“,NSLocalizedDescription =已加载无法处理响应(200),内容类型为'application / json'}

更新
这是我处理这种情况的最后一段代码。它可能对其他人有用......

// Manually Map Request to JSON & send to server
NSDictionary *parameters = [RKObjectParameterization parametersWithObject:payload requestDescriptor:[payload.class requestDescriptor] error:&error];
NSMutableURLRequest* request = [self.apiManager requestWithObject:nil method:RKRequestMethodPOST path:url parameters:parameters];

RKHTTPRequestOperation *requestOperation = [[RKHTTPRequestOperation alloc] initWithRequest:request];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    unichar firstChar = [operation.responseString characterAtIndex:0];
    NSData *newData;
    if (firstChar != '{' && firstChar != '[') {
        // Force into JSON array so it can be parsed normally
        newData = [[[@"[" stringByAppendingString:operation.responseString] stringByAppendingString:@"]"] dataUsingEncoding:NSUTF8StringEncoding]; 
    } else {
        newData = operation.responseData;
    }

    // Parse JSON response into native object, whether primitive NSNumber (integer or boolean) response or a full fledged JSON error object.
    RKResponseDescriptor *errDescriptor = [MyErrorResponse responseDescriptor];
    RKObjectResponseMapperOperation* mapper = [[RKObjectResponseMapperOperation alloc] initWithRequest:request response:operation.response data:newData responseDescriptors:@[errDescriptor, [payload.class responseDescriptor]]];
    [mapper setDidFinishMappingBlock:^(RKMappingResult *mappingResult, NSError *error) {
        if (mappingResult) { //Success
            RKLogInfo(@"Load response: %@", mappingResult.firstObject);
        } else {
            RKLogError(@"Operation failed with error: %@", error);
        }
    }];
    [mapper start];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    RKLogError(@"Operation failed with error: %@", error);
}];

[requestOperation start];

1 个答案:

答案 0 :(得分:1)

  

我看到了使用RestKit构建请求的建议,并将其传递给AFNetworking

是的,那样做。

  

但这不会解析可能的错误返回对象

是的,但你可以在RestKit中使用映射操作来处理它。或者,如果错误响应相对简单,只需使用NSJSONSerialization(或类似)转换响应。


'原始ID'应该可以映射nil-keypath。但是,如果未将错误响应映射回POST请求中使用的源对象,则可能仍存在映射错误响应的问题。