我有这门课:
@interface MovieStatus : NSObject
@property (nonatomic, strong) NSNumber* seen;
@property (nonatomic, strong) NSNumber* watchlist;
@end
其中两个属性都表示可选的可为 null 的 bool 值。我通过 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
}
谁能指出我如何实现它?
最佳答案
我通过将映射的 assignsDefaultValueForMissingAttributes
设置为 NO
解决了这个问题:
requestMapping.assignsDefaultValueForMissingAttributes = NO;
现在 JSON 请求不包含 null
值。
关于ios - 使用 RestKit 序列化 JSON 时忽略 nil 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24139616/