2013-05-07 79 views
0

我想找到一種方法來正確地將對象集合映射到具有特定格式的JSON字典。用RestKit集合上的自定義請求映射0.20

我有以下接口的對象(部分):

@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的方式。

在此先感謝。

+0

您正在尋找的輸出不是我所謂的JSON清潔使用,所以我不認爲實際上有一種方法可以使用RestKit來完成。你需要自己做。出於興趣,爲什麼你需要這種形式的JSON? – Wain 2013-05-08 15:43:24

+0

感謝您的回覆。我同意格式不符合標準。最後,我可以讓API負責人修改它以接受標準格式的「接收者」:[{「id」:「」},...] – 2013-05-10 06:54:24

回答

1

,如果你想這樣做,是你需要的,正如你所說,使用NSMutableURLRequest並添加賦予的NSString與您的JSON你的獎勵方法請求這個簡單的代碼可以幫助你和其他開發商像我這樣的:

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

我希望它可以幫助某人