【问题标题】:How can you send a nested object in the body of an Alamofire API request?如何在 Alamofire API 请求的主体中发送嵌套对象?
【发布时间】:2020-07-13 15:16:39
【问题描述】:

我尝试使用 Alamofire 发出这样的 API 请求:

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'

根据需要,它给了我这样的回应:

{
    "id":"xy",
    "products":[
        {
            "quantity":2,
            "product":{
                "id":123
            }
        }
    ]
}

【问题讨论】:

标签: swift alamofire-request


【解决方案1】:

您需要以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 会为您解决这些问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2016-12-25
    • 2020-06-19
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多