Similar questions to this have been posted before but with slight differences, namely:
Alamofire: Sending JSON as request parameter
POST multiple json objects in Alamofire POST method - Swift/IOS
Sending json array via Alamofire
being the last one, the closest to my current problem. However, this solution is not working for me.
The problem I am facing is that I'm trying to send through an Alamofire POST request, a JSON that I've built using SwiftyJSON. Like so:
let url = NSURL(string: orderProductsEndpoint)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue(requestToken, forHTTPHeaderField: "Authorization:")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let params = [ json.object ]
print(params)
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject( params, options: [])
Alamofire.request(request)
.responseString{ response in
switch response.result {
case .Success(let value):
print("gut")
print(value)
case .Failure(let error):
print("not gut")
print(error)
}
}
However, this is not working well because the API that I'm communicating with doesn't seem to recognize well the parameters that I'm sending.
But then I noticed that what I am sending is not a valid JSON. This is what I am sending:
[{
car = (
{
cant = 2;
id = 6;
name = "Saudi Plate";
},
{
cant = 1;
id = 5;
name = "Beef Wrap";
}
);
idUser = 58;
"total_loyalty_points" = 4200;
"total_price" = 42000;}]
But before converting my JSON to an object using
let params = [ json.object ]
It was a valid JSON validated through JSONLint and it looks like this
{
"total_price" : 42000,
"car" : [
{
"id" : "6",
"cant" : 2,
"name" : "Saudi Plate"
},
{
"id" : "5",
"cant" : 1,
"name" : "Beef Wrap"
}
],
"idUser" : 58,
"total_loyalty_points" : 4200
}
So the problem is that I was forced to change the structure of the JSON because it seems to be the only way to send it through Alamofire, by converting it into an object. Is there a way to actually send raw JSON through Alamofire?