0

我正在使用 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 的服务器端?有任何想法吗?

谢谢

4

1 回答 1

0

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

您需要 2 个映射:

  1. 参数字典
  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];

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

于 2013-05-15T06:19:55.737 回答