RestKit POST对象为Python

时间:2013-05-15 03:38:44

标签: python ios flask restkit

我正在使用RestKit for iOS对我的Python(Flask)服务器执行POST。 POST参数是一组嵌套的字典。当我在客户端创建分层参数对象并执行帖子时,没有错误。但是在服务器端,表单数据被扁平化为一组键,这些键本身就是索引字符串:

@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?有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

错误在于客户端映射。您的映射需要表示所需数据的结构及其包含的关系。目前,映射使用了有效隐藏结构关系的键路径。

您需要2个映射:

  1. 参数字典
  2. 词典的容器
  3. 映射定义为:

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

    然后使用容器映射定义您的请求描述符。