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. 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. Any suggestions are much appreciated!
parameters
dictionary, the key for the array is@"orders"
– Ecstaticmanager.requestSerializer = [AFJSONRequestSerializer serializer];
as mentioned in the accepted answer. – Kingfisher