Search code examples
restkit

RestKit Mapping for POSTing JSON List


Is it possible use RestKit to POST a request to a server that expects a JSON list of dictionaries? :

[
  { "key1":"value1",
    "key2":"value2"
  }
]

The wiki: https://github.com/RestKit/RestKit/wiki/Object-Mapping#mapping-without-kvc describes how this can be done on a response - mapping from JSON to objects - but not the other way around - objects to JSON. To complicate the problem I think, the URL request is of the form http://www.example.com/some-name/upload - not very restful.

Thanks for any help.

Edit:

Thanks Wain to force me to look deeper to find a solution - I wasn't sure it was possible. Based on RestKit issue 398 documented by blakewatters I solved the problem like this:

RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:@{@"key1":@"value1", @"key2":@"value2"}];


RKRequestDescriptor *requestDescriptor =
[RKRequestDescriptor requestDescriptorWithMapping:requestMapping
                                      objectClass:[MyObjectClass class]
                                      rootKeyPath:nil
                                           method:RKRequestMethodPOST];

[objectManager addRequestDescriptor:requestDescriptor];


[[RKObjectManager sharedManager] postObject:@[self.myObject]
                                       path:@"/path/myobject/upload"
                                 parameters:nil
                                    success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                        NSLog(@"Success!");
                                    }
                                    failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                        NSLog(@"Fail.");
                                    }];

I think key was to put myObject in an array, and then set "rootKeyPath" and "parameters" to nil.


Solution

  • Sure it can, it's basically the same thing (mapping) then use inverseMapping and a request descriptor instead of a response descriptor.

    You'll want a response descriptor anyway as you need to handle the response...