使用RestKit序列化JSON时忽略nil属性

时间:2014-06-10 11:15:28

标签: ios objective-c json restkit

我有这堂课:

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

其中两个属性表示可选的可空布尔值。我通过RKObjectManager使用RestKit将此对象发送到服务器并创建了适当的映射。但在序列化对象时,我无法从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
}

任何人都可以指出我如何实现它?

1 个答案:

答案 0 :(得分:9)

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

requestMapping.assignsDefaultValueForMissingAttributes = NO;

现在,JSON请求不包含null个值。