我有一个情况,我正在做一个对象的发布(不是一个管理的,只是一个NSObject派生的),但REST API的响应不是要发布的对象的
JSON表示形式.这还有别的东西.是否可以处理这个?
说我发布一个对象(JSON):
{ "prop1" : 123,"prop2" : 5 }
而且如果不是具有属性prop1和prop2的对象(如RestKit预期的那样),而是其他的东西:
{ "data" : [1,2,3,4,5,6],"message" : "hello world" }
我已经看到一些例子,其中将operation.targetObject设置为nil,但(我相信)这只是在Core Data管理的场景中.
我正在尝试像这样简单的东西:
RKObjectRequestOperation *operation = [self.objectManager appropriateObjectRequestOperationWithObject:body method:RKRequestMethodPOST path:@"items" parameters:nil]; [operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation,RKMappingResult *result) { // success is called,but the result does not contain what the response JSON is } failure:^(RKObjectRequestOperation *operation,NSError *error) { // failure }]; [operation setWillMapDeserializedResponseBlock:^id(id deserializedResponseBody) { // deserializedResponseBody is always nil }]; [operation start];
我以为我可以看看setWillMapDeserializedResponseBlock中的响应内容,但总是为零.
因为发布的对象具有prop1和prop2属性,以及RestKit默认情况下的工作原理,它期望具有所述属性的JSON.但是,由于结果与发布的对象无关,所以prop1和prop2只是零(我不在乎).
顺便说一下,我已经正确地设置了请求映射,所以在操作对象中传递的正文正确映射我的NSObject并以正确的JSON格式发送给服务器.
有没有办法,我可以用RestKit打电话,手动拔出我正在寻找的成功事件?即使它是JSON响应的字典表示法?
@R_403_323@
我只是为您的回应创建一个新对象,并将您的回复映射到该对象.
对象
@interface MYRequest : NSObject @property NSNumber *prop1; @property NSNumber *prop2; @end @interface MYResponse : NSObject @property NSArray *data; @property NSString *message; @end
映射
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping]; [requestMapping addAttributeMappingsFromArray:@[@"prop1",@"prop2"]]; RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[MYResponse class]]; [requestMapping addAttributeMappingsFromArray:@[@"data",@"message"]];
叙
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[MYRequest class] rootKeyPath:nil method:RKRequestMethodPOST]; RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodPOST pathPattern:@"items" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
对象管理器
[self.objectManager addRequestDescriptor:requestDescriptor]; [self.objectManager addResponseDescriptor:responseDescriptor];
执行
MYRequest *body = [MYRequest new]; [body setProp1:@123]; [body setProp2:@5]; [self.objectManager postObject:body path:@"items" parameters:nil success:^(RKObjectRequestOperation *operation,RKMappingResult *mappingResult) { MYResponse *result = [mappingResult firstObject]; NSLog(@"Data: %@\nMessage: %@",[result data],[result message]); } failure:^(RKObjectRequestOperation *operation,NSError *error) { NSLog(@"Error: %@",error); }];