gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:43:37 24 4
gpt4 key购买 nike

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

最佳答案

我看不到您指定要发布 JSON 的位置,所以我打赌您发送的是表单 URL 参数编码,根据 AFHTTPClient 文档,它是这样的:

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. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the -description method. The constructed query string does not include the ? character used to delimit the query component.

如果您的服务器确实希望您发布 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: 方法中的配置。 (您可能不想为每个请求启动一个新客户端。)

关于ios - AFNetworking 在 post 请求的 JSON 参数中发送数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com