Mas*_*son 6 arrays post json ios 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];
Run Code Online (Sandbox Code Playgroud)
但是,发送此JSON时出错.任何建议都非常感谢!
根据AFHTTPClient文档,我没有看到你指定要发布JSON的位置,所以我打赌你发送的是表格URL参数编码,就像这样:
如果查询字符串对
NSArray的值为a,则数组的每个成员都将以该格式表示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;
Run Code Online (Sandbox Code Playgroud)
然后,您将删除您的呼叫NSJSONSerialization并将其objectsInCart放入parameters字典中.
附注:子类AFHTTPRequestOperationManager或AFHTTPSessionManager(AFNetworking 2.0)或AFHTTPClient(AFNetworking 1.0)是正常的,并将此类配置放在您的initWithBaseURL:方法中.(您可能不希望为每个请求启动新客户端.)