Swift:使用JSON Object作为正文的Alamofire POST请求

问题描述 投票:2回答:1

我有这个要求:

curl -X "POST" "myURL" \
-H 'Content-Type: application/json' \
-H 'User-Agent: myAgent)' \
-H 'Accept-Language: it-IT' \
-d $'{ "Summary": { "Discount": 1.099, "TotalAmount": 9.891, "SubtotalAmount": 10.99 }, "Token": "token", "InstantDiscountId": "id" }'

但我不知道如何使用该JSON对象设置正文。使用Alamofire,我总是在请求中使用[String:Any]作为参数但事实并非如此。

json swift post alamofire
1个回答
0
投票

答案是简单地将编码设置为JSONEncoding.default

以下是代码的外观

let request = Alamofire.request(
    myUrl,
    method: .post,
    parameters: [
        "Summary": [
            "Discount": 1.099,
            "TotalAmount": 9.891,
            "SubtotalAmount": 10.99
        ],
        "Token": "token",
        "InstantDiscountId": "id"
    ],
    encoding: JSONEncoding.default,
    headers: [
        "Content-Type": "application/json",
        "User-Agent": "myAgent",
        "Accept-Language": "it-IT"
    ]
)
© www.soinside.com 2019 - 2024. All rights reserved.