Posting an array of JSON strings using RestKit

I have the following object

@interface MyObject : NSObject @property(nonatomic, copy) NSNumber *objectId; @property(nonatomic, copy) NSArray *tags; // array of strings, eg @[@"one", @"two"] @end 

I would like to send a request using RestKit (version 0.23) in the URL

 <base_url>/do_something/:objectId 

The request body should be just an array of JSON strings according to the tags property, i.e.

 ["one", "two"] 

I have a specific route.

 RKRoute *route = [RKRoute routeWithClass: [MyObject class] pathPattern: do_something/:objectId method: RKRequestMethodPOST]; [objectManager.router.routeSet addRoute: route]; 

Now I would like to create a query

 [objectManager requestWithObject: instanceOfMyObject method: RKRequestMethodPOST path: nil parameters: nil]; 

How do I configure [RKObjectMapping requestMapping] and how should I define an RKRequestDescriptor to get the above mapping (array of JSON strings)?

I tried the following:

 RKObjectMapping *requestMapping = [RKObjectMapping requestMapping]; [requestMapping addPropertyMapping: [RKAttributeMapping attributeMappingFromKeyPath: @"tags" toKeyPath: nil]]; RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping: requestMapping objectClass: [MyObject class] rootKeyPath: nil method: RKRequestMethodAny]; 

However, using nil as the key path in RKAttributeMapping fails. Using any value other than zero, in the request its body is a JSON dictionary

 {"someKeyPath": ["one", "two"]} 
0
source share
1 answer

I believe that RestKit was designed taking into account that you should place an object instead, for example. {"tags": [ "tag1", "tag2" ]} . Same thing with the answers; if the body is not an object (and just a raw string or array), RestKit will not handle it well.

In this case, you can serialize the request yourself and send it to the body. For instance:

 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]; 
0
source

Source: https://habr.com/ru/post/1500821/


All Articles