如何在Alamofire API请求的正文中发送嵌套对象?

时间:2020-07-13 15:16:39

标签: swift alamofire-request

我试图使用Alamofire发出如下API请求:

<%= link_to 'Nouvelle partie', games_path, method: :post, class: 'regular-btn' %>

我收到了此回复:

let param = ["id":"xy", "products":[["quantity":2, "product":["id":123]]]]

Alamofire.request(url, method: .post,
                   parameters: param, encoding: URLEncoding.default, 
                      headers: ["Accept": "application/json", "Content-Type": "application/json"]).responseJSON ..

我也尝试过这样的请求:

message = "Unexpected token i in JSON at position 0";
statusCode = 400;

我尝试手动执行以下请求,以确保其运行正常:

request.httpBody = try! JSONSerialization.data(withJSONObject: param)

根据需要,它给了我以下答复:

curl -X POST http://url -d'{"id":"xy", "products" [{"quantity":2,"product":{"id":123}}]}' -H'Content-Type: application/json'

1 个答案:

答案 0 :(得分:2)

您需要以application/json的形式发送请求,所以请使用JSONEncoding.default作为encoding的参数。

Alamofire.request( url, method: .post , parameters: param, encoding: JSONEncoding.default , headers: ["Accept": "application/json",
                      "Content-Type": "application/json"])

附加组件:另外,您可以从标头参数中删除Content-TypeAF会为您解决这个问题。