Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore nil properties when serializing JSON using RestKit

I have this class:

@interface MovieStatus : NSObject
@property (nonatomic, strong) NSNumber* seen;
@property (nonatomic, strong) NSNumber* watchlist;
@end

Where both properties represent optional nullable boolean values. I'm sending this object to the server using RestKit through the RKObjectManager and created the appropriate mapping. But I'm unable to skip the property from the POST data when serializing the object.

For example, this code:

RKLogConfigureByName("*", RKLogLevelTrace);

RKObjectManager* manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://www.example.com/v1"]];
manager.requestSerializationMIMEType = RKMIMETypeJSON;

RKObjectMapping* requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromArray:@[@"seen", @"watchlist"]];

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

RKRoute* route = [RKRoute routeWithClass:[MovieStatus class] pathPattern:@"status" method:RKRequestMethodPOST];
[manager.router.routeSet addRoute:route];


MovieStatus* status = [[MovieStatus alloc] init];
status.seen = @(YES);
[manager postObject:status path:nil parameters:nil success:nil failure:nil];

is sending the JSON:

{
  "seen": true,
  "watchlist": null
}

Where I'd like to send:

{
  "seen": true
}

Can anyone point me out how can I achieve it?

like image 952
redent84 Avatar asked Jun 10 '14 11:06

redent84


1 Answers

I solved it by setting the assignsDefaultValueForMissingAttributes of the mapping to NO:

requestMapping.assignsDefaultValueForMissingAttributes = NO;

Now the JSON request doesn't contain null values.

like image 108
redent84 Avatar answered Nov 15 '22 04:11

redent84