AFNetworking在post请求的JSON参数中发送数组

时间:2013-08-20 18:08:58

标签: ios arrays json post afnetworking

我正在尝试通过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时出错。任何建议都非常感谢!

1 个答案:

答案 0 :(得分: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:方法中。 (您可能不希望为每个请求启动新客户端。)