2013-05-15 65 views
0

我正在使用RestKit for iOS對我的Python(Flask)服務器執行POST。 POST參數是一組嵌套字典。當我在客戶端創建我的層次參數對象並執行帖子時,沒有錯誤。但是在服務器端,表單數據被壓扁成一個單一的一套鑰匙其本身索引的字符串:RestKit POST對象到Python

@interface TestArgs : NSObject 

@property (strong, nonatomic) NSDictionary *a; 
@property (strong, nonatomic) NSDictionary *b; 

@end 


RKObjectMapping *requestMapping = [RKObjectMapping requestMapping]; // objectClass == NSMutableDictionary 
[requestMapping addAttributeMappingsFromArray:@[ 
@"a.name", 
@"a.address", 
@"a.gender", 
@"b.name", 
@"b.address", 
@"b.gender", 
]]; 

RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[TestArgs class] rootKeyPath:nil]; 

RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://localhost:5000"]]; 
[manager addRequestDescriptor:requestDescriptor]; 

NSDictionary *a = [NSDictionary dictionaryWithObjectsAndKeys: 
        @"Alexis", @"name", 
        @"Boston", @"address", 
        @"female",  @"gender", 
        nil]; 
NSDictionary *b = [NSDictionary dictionaryWithObjectsAndKeys: 
        @"Chris", @"name", 
        @"Boston", @"address", 
        @"male",  @"gender", 
        nil]; 
TestArgs *tArgs = [[TestArgs alloc] init]; 
tArgs.a = a; 
tArgs.b = b; 

[manager postObject:tArgs path:@"/login" parameters:nil success:nil failure:nil]; 

在服務器端,POST體是這樣的:

{'b[gender]': u'male', 'a[gender]': u'female', 'b[name]': u'Chris', 'a[name]': u'Alexis', 'b[address]': u'Boston', 'a[address]': u'Boston'} 

當什麼我真正想要的是這樣的:

{'b': {'gender' : u'male', 'name': u'Chris', 'address': u'Boston'}, 'a': {'gender': u'female', 'name': u'Alexis', 'address': u'Boston'}} 

爲什麼POST正文沒有在服務器端維護其層次結構?這是我的客戶端編碼邏輯錯誤嗎?在服務器端用Flask解碼JSON?有任何想法嗎?

謝謝

回答

0

錯誤是與客戶端映射。您的映射需要表示所需數據的結構及其包含的關係。目前,映射使用有效隱藏結構關係的關鍵路徑。

您需要2個映射:

paramMapping = [RKObjectMapping requestMapping]; 
containerMapping = [RKObjectMapping requestMapping]; 

[paramMapping addAttributeMappingsFromArray:@[ 
@"name", 
@"address", 
@"gender", 
]]; 

RKRelationshipMapping *aRelationship = [RKRelationshipMapping 
             relationshipMappingFromKeyPath:@"a" 
             toKeyPath:@"a" 
             withMapping:paramMapping]; 
RKRelationshipMapping *bRelationship = [RKRelationshipMapping 
             relationshipMappingFromKeyPath:@"b" 
             toKeyPath:@"b" 
             withMapping:paramMapping] 

[containerMapping addPropertyMapping:aRelationship]; 
[containerMapping addPropertyMapping:bRelationship]; 

那麼你的請求描述:

  1. 的參數
  2. 字典

的映射的容器被定義爲詞典是使用容器映射定義的。