Search code examples
iosobjective-cios6restkitrestkit-0.20

How to map a NSArray with NSStrings in the request (RESTKit)


I got a problem with a request mapping in Restkit 0.20. I want to put a NSArray with NSStrings into the request under the the key "mails" e.g.:

{mails:[@"[email protected]",@"[email protected]"]}

So, for this case I don't really need an object mapping, cause I am using only standard objects. I just didn't get it to work, so I switched back to the regular way (at least for me) - introducing a DTO object MailRequest which contains the NSArray. I do it like this:

RKObjectMapping* mapping =  [RKObjectMapping requestMapping];
[mapping addAttributeMappingsFromDictionary:@{
        @"mails":@"mails"
}];  

RKRequestDescriptor *reqDesc = 
            [RKRequestDescriptor requestDescriptorWithMapping:mapping
                                                  objectClass:[MailRequest class]
                                                  rootKeyPath:nil];

RKObjectManager *manager = ...
...
NSMutableURLRequest *request = [manager requestWithObject:requestObject 
                                                   method:RKRequestMethodPOST 
                                                     path:urlString parameters:nil];

RKObjectRequestOperation *operation = 
                     [manager objectRequestOperationWithRequest:request ...

... but I would like to get rid of the MailsRequest DTO object. Is that possible?


Solution

  • Skip the mapping step and just use RestKit for the send and any response mapping. Build your dictionary any way you want. You do need to create the URL from urlString.

    NSDictionary *mails = @{mails:@[@"[email protected]",@"[email protected]"]};
    NSError *error = nil;
    NSData *mailsJSON = [NSJSONSerialization dataWithJSONObject:mails options:0 error:&error];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:mailsJSON];
    
    RKObjectRequestOperation *operation = [manager objectRequestOperationWithRequest:request ...