如何將多個對象映射到一個JSON對象?爲RestKit合併對象
這裏是我的兩個對象
#import <RestKit/RestKit.h>
@interface Account : NSObject
@property NSInteger id;
@property NSString* secret;
@end
@implementation Account @end
@interface Entry : NSObject
@property NSString* name;
@end
@implementation Entry @end
而且我希望這些對象映射到以下JSON:
/* Goal JSON:
{
"id":10,
"secret":"supersecret",
"eventName":"Hayooo"
}
*/
第一次嘗試直接使用RKMapperOperation:
void testMergeMap(){
Account* account = [Account new];
account.id = 10;
account.secret = @"supersecret";
Entry* entry = [Entry new];
entry.name = @"Hayooo";
RKMapperOperation* mapper = [[RKMapperOperation alloc]
initWithRepresentation:@{@"account":account, @"entry":entry} mappingsDictionary:@{@"account.id": @"id", @"account.secret":@"secret", @"entry.name":@"eventName"}];
[mapper start];
RKMappingResult* result = mapper.mappingResult;
NSLog(@"%@", result.dictionary.description);
}
但是,這崩潰,不能真正使錯誤的東西。
那麼,我該怎麼做呢?
編輯
我也試過這個
RKObjectManager* testSimpleMap(Account* account, Entry* entry){
RKObjectMapping* map = [RKObjectMapping requestMapping];
[map addAttributeMappingsFromDictionary:
@{@"account.id": @"id",
@"account.secret": @"secret",
@"entry.name":@"eventName"}];
RKObjectManager* man = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://google.com"]];
RKRequestDescriptor* requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:map objectClass:nil rootKeyPath:nil method:RKRequestMethodPOST];
[man addRequestDescriptor:requestDescriptor];
[man postObject:@{@"account":account, @"entry":entry} path:@"/" parameters:nil success:nil failure:nil];
return man;
}
但是,如果沒有一個類,所以不能創建requestDescriptors,這樣是行不通的。但我認爲了解我的目標很有用。如果那能行得通,那會很棒!
隨意編輯,請不要以這種方式進行編輯,它不能複製並粘貼到編輯器中。我小心翼翼地讓它自成一體,不要毀了它。 – Nick