0

我正在尝试找到一种将对象集合正确映射到具有特定格式的 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

目标是发布一个奖励对象以及接收者属性。

我可以想出一个适用于标题评论属性的 RKObjectMapping,但接收器集合需要以下格式:

"receivers":{"0":"<user_id_of_first_user>", "1":"<user_id_of_second_user>", ...}

我的主要问题是如何将索引作为键插入。

我可以手动完成并调整 NSURLRequest HTTPBody,但我希望找到一种更干净/RestKit 的方式。

提前致谢。

4

1 回答 1

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

我希望它对某人有帮助

于 2014-05-22T07:39:37.707 回答