我有以下对象
@interface MyObject : NSObject
@property(nonatomic, copy) NSNumber *objectId;
@property(nonatomic, copy) NSArray *tags; // array of strings, e.g. @[@"one", @"two"]
@end
我想使用RestKit(版本0.23)将请求发布到URL
<base_url>/do_something/:objectId
根据tags
属性,请求体应该只是一个JSON字符串数组,即
["one", "two"]
我定义了一条路线。
RKRoute *route = [RKRoute routeWithClass: [MyObject class] pathPattern: do_something/:objectId method: RKRequestMethodPOST];
[objectManager.router.routeSet addRoute: route];
现在,我想创建一个请求
[objectManager requestWithObject: instanceOfMyObject method: RKRequestMethodPOST path: nil parameters: nil];
我应该如何配置[RKObjectMapping requestMapping]
以及如何定义RKRequestDescriptor
以获取上面的映射(JSON字符串数组)?
我尝试了以下内容:
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addPropertyMapping: [RKAttributeMapping attributeMappingFromKeyPath: @"tags" toKeyPath: nil]];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping: requestMapping objectClass: [MyObject class] rootKeyPath: nil method: RKRequestMethodAny];
但是,在nil
崩溃中使用RKAttributeMapping
作为关键路径。使用任何not-nil值会导致请求其主体是JSON字典
{"someKeyPath": ["one", "two"]}
答案 0 :(得分:0)
我相信RestKit的设计理念是你应该发布一个对象,例如。 {"tags": [ "tag1", "tag2" ]}
。与回应相同;如果正文不是一个对象(只是一个原始字符串或数组),RestKit就不会很好地处理它。
话虽如此,您可以自己序列化请求并将其发布到正文中。例如:
NSMutableURLRequest *request = [[objectManager requestWithObject:nil method:RKRequestMethodPOST path:@"do_something/objectId" parameters:nil] mutableCopy];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:doableIds options:0 error:nil]];
RKObjectRequestOperation *operation = [objectManager objectRequestOperationWithRequest:request success:nil failure:nil];
[objectManager enqueueObjectRequestOperation:operation];