简体   繁体   English

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

[英]AFNetworking send array in JSON parameters of post request

I'm trying to send parameters to my server via POST, and it works generally, but I can't figure out how to send JSON that contains an array as one of the parameters. 我正在尝试通过POST将参数发送到我的服务器,它通常可以正常工作,但我无法弄清楚如何发送包含数组的JSON作为参数之一。 Here's what I've tried: 这是我尝试过的:

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

However, I get an error when sending this JSON. 但是,发送此JSON时出错。 Any suggestions are much appreciated! 任何建议都非常感谢!

I don't see where you're specifying you want to post JSON, so I'm betting you're sending Form URL Parameter Encoding, which goes like this, according to the AFHTTPClient documentation: 根据AFHTTPClient文档,我没有看到你指定要发布JSON的位置,所以我打赌你发送的是表格URL参数编码,就像这样:

If a query string pair has a an NSArray for its value, each member of the array will be represented in the format field[]=value1&field[]=value2 . 如果查询字符串对的值为NSArray ,则数组的每个成员都将以格式field[]=value1&field[]=value2 Otherwise, the pair will be formatted as "field=value". 否则,该对将被格式化为“field = value”。 String representations of both keys and values are derived using the -description method. 使用-description方法派生键和值的字符串表示。 The constructed query string does not include the ? 构造的查询字符串不包含? character used to delimit the query component. 用于分隔查询组件的字符。

If your server is indeed expecting you to post JSON, add this on the second line to tell AFNetworking that: 如果您的服务器确实希望您发布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;

You would then remove your call to NSJSONSerialization and just put objectsInCart into the parameters dictionary. 然后,您将删除对NSJSONSerialization的调用,并将objectsInCart放入parameters字典中。

A side note: it's normal to subclass AFHTTPRequestOperationManager or AFHTTPSessionManager (AFNetworking 2.0) or AFHTTPClient (AFNetworking 1.0) and put this type of configuration in your initWithBaseURL: method. 附注: AFHTTPRequestOperationManagerAFHTTPSessionManager (AFNetworking 2.0)或AFHTTPClient (AFNetworking 1.0)的子类是正常的,并将此类配置放在initWithBaseURL:方法中。 (You probably don't want to spin up a new client for every request.) (您可能不希望为每个请求启动新客户端。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM