6

我正在尝试通过 POST 将参数发送到我的服务器,它通常可以工作,但我无法弄清楚如何发送包含数组作为参数之一的 JSON。这是我尝试过的:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:myURL]];
NSMutableArray *objectsInCart = [NSMutableArray arrayWithCapacity:[_cart count]];
for(NSDictionary *dict in _cart)
{
    NSObject *object = [dict objectForKey:@"object"];
    NSDictionary *objectDict = @{@"product_id": [NSString stringWithFormat:@"%d",[object productID]],
                                 @"quantity": [NSString stringWithFormat:@"%d", [[dict objectForKey:@"count"] intValue]],
                                 @"store_id": [NSString stringWithFormat:@"%d", [Store getStoreID]],
                                 @"price": [NSString stringWithFormat:@"%.2f", [object price]]};
    [objectsInCart addObject:objectDict];
}
NSError *error = nil;
NSString *cartJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:objectsInCart
                                                                                    options:NSJSONWritingPrettyPrinted
                                                                                      error:&error]
                                           encoding:NSUTF8StringEncoding];

if(error)
{
    NSLog(@"Error serializing cart to JSON: %@", [error description]);
    return;
}

NSDictionary *parameters = @{@"status": @"SUBMITTED",
                             @"orders": cartJSON};

NSMutableURLRequest *orderRequest = [httpClient requestWithMethod:@"POST"
                                                             path:@"/app/carts"
                                                       parameters:parameters];

AFJSONRequestOperation *JSONOperation = [[AFJSONRequestOperation alloc] initWithRequest:orderRequest];

但是,发送此 JSON 时出现错误。任何建议都非常感谢!

4

1 回答 1

9

根据 AFHTTPClient 文档,我没有看到您指定要在哪里发布 JSON,所以我打赌您正在发送表单 URL 参数编码,如下所示:

如果查询字符串对的NSArray值有一个,则数组的每个成员都将以格式表示field[]=value1&field[]=value2。否则,该对将被格式化为“field=value”。键和值的字符串表示都是使用该-description方法派生的。构造的查询字符串不包括?用于分隔查询组件的字符。

如果您的服务器确实希望您发布 JSON,请将其添加到第二行以告诉 AFNetworking:

// AFNetworking 1.0
// httpClient is a subclass of AFHTTPClient
httpClient.parameterEncoding = AFJSONParameterEncoding;

// AFNetworking 2.0
// httpClient is a subclass of AFHTTPRequestOperationManager or AFHTTPSessionManager
httpClient.requestSerializer = AFJSONRequestSerializer;

然后,您将删除您的呼叫NSJSONSerialization并放入objectsInCart字典parameters中。

附注:继承AFHTTPRequestOperationManagerAFHTTPSessionManager(AFNetworking 2.0) 或AFHTTPClient(AFNetworking 1.0) 并将这种类型的配置放入您的initWithBaseURL:方法中是正常的。(您可能不想为每个请求启动一个新客户端。)

于 2013-08-21T01:00:00.513 回答