我正在尝试找到一种方法,将对象集合正确映射到具有特定格式的JSON字典。
我有一个带有以下界面的对象(部分):
@interface Reward : NSObject
...
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* comment;
@property (nonatomic, strong) NSMutableOrderedSet* receivers; //set of User
...
@end
用户对象(部分)是:
@interface User : NSManagedObject
...
@property (nonatomic, strong) NSNumber* userId
...
@end
目标是POST一个Reward对象以及 receiver 属性。
我可以想出一个适用于 title 和 comment 属性的RKObjectMapping,但 receiver 集合需要以下格式:
"receivers":{"0":"<user_id_of_first_user>", "1":"<user_id_of_second_user>", ...}
我的主要问题是如何将索引作为键插入。
我可以手动完成并调整NSURLRequest HTTPBody,但我希望找到更干净/ RestKit方式。
提前致谢。
答案 0 :(得分:1)
如果您想要这样做,正如您所说,使用NSMutableURLRequest并添加您的奖励方法请求,该请求为您的json提供NSString这个简单的代码可以帮助您和像我这样的其他开发人员:
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];
我希望它有助于某人