0

I'm trying to find a way to properly map a collection of objects to a JSON dictionary with a specific format.

I have an object with the following interface (partial):

@interface Reward : NSObject
...
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* comment;
@property (nonatomic, strong) NSMutableOrderedSet* receivers; //set of User
...
@end

And the User object (partial) is:

@interface User : NSManagedObject
...
@property (nonatomic, strong) NSNumber* userId
...
@end

The goal is to POST a Reward object, along with the receivers property.

I could come up with an RKObjectMapping that works for title and comment attributes, but the receivers collection requires the following format:

"receivers":{"0":"<user_id_of_first_user>", "1":"<user_id_of_second_user>", ...}

My main problem is how to insert the index as a key.

I could do it manually and tweak the NSURLRequest HTTPBody, but I was hoping to find a more clean/RestKit way.

Thanks in advance.

Loïc Gardiol
  • 361
  • 3
  • 7
  • The output you're looking for isn't what I'd call a clean use of JSON so I don't think there is actually a way to do it with RestKit. You'll need to do it yourself. Out of interest, why do you need the JSON in that form? – Wain May 08 '13 at 15:43
  • Thanks for your reply. I agree on the fact that the format was not standard. In the end, I could make the person responsible for the API to modify it to accept a standard format "receivers":[{"id":""}, ...] – Loïc Gardiol May 10 '13 at 06:54

1 Answers1

1

if you want to do that's you need, as you said, use NSMutableURLRequest and add in your reward method request which gives NSString with your json this simple code can help you and other developers like me:

RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[RKObjectManager baseUrl]];
Reward *reward = [[Reward alloc] init];
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Reward class]];
RKResponseDescriptor *desc = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodPOST pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

[manager addResponseDescriptor:desc];
RKObjectManager *objectManager = [RKObjectManager sharedManager];
NSMutableURLRequest *request =
[objectManager requestWithObject:reward method:RKRequestMethodPOST path:@"yourpath" parameters:nil];
 NSString *str = [NSString stringWithFormat:@"\"receivers\":%@",reward.request];
[request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[desc]];
[operation setCompletionBlockWithSuccess:success failure:failure];
operation.targetObject = reward;
[operation start];

I hope it`s help someone

Sergio
  • 319
  • 4
  • 19