0

iOS 用の RestKit を使用して、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 に答える