2014-06-10 37 views
5

序列化JSON当我有这个类:忽略零特性采用RestKit

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

如果这两个属性表示可选为空的布尔值。我使用RestKit通过RKObjectManager将此对象发送到服务器,并创建了适当的映射。但是当序列化对象时,我无法从POST数据跳过属性。

例如,下面的代码:

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

在发送JSON:

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

在哪里,我想送:

{ 
    "seen": true 
} 

任何人都可以点我如何我可以实现它吗?

回答

9

我解决它通过映射的assignsDefaultValueForMissingAttributes设置为NO

requestMapping.assignsDefaultValueForMissingAttributes = NO; 

现在JSON请求不包含null值。

+1

有没有办法在全局范围内设置而不是为每个映射单独设置? – dirkoneill

+0

你可以继承RKObjectMapping – VaporwareWolf

+1

这对我不起作用,我也认为这是默认设置为“NO”的意思吗? 我已经发布了一个新的问题在http://stackoverflow.com/questions/31846262/how-do-i-ignore-empty-properties-on-posted-objects-using-restkit – Tim