Alamofire在正文中发送json

问题描述 投票:0回答:1
let urlString = "***********"


            let url = URL(string: urlString)!

            let headers: HTTPHeaders = ["Content-Type" : "application/json"]
            var request = URLRequest(url: url)
            request.headers = headers
            request.httpMethod = HTTPMethod.post.rawValue
            request.httpBody = json?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
          //  request.httpBody =  json?.data(using: .utf8)

            print(json!)

            AF.request(request).responseJSON {
                (response) in
                print(response)
            }

它不起作用,我需要将主体中的json作为字符串发送,如下所示。我正在使用Swift 5。

{ "name":"John", "age":30, "car":null }

等效的android通话

val gson = Gson()
        val op = MultipartBody.Builder()
        val jsonInString = gson.toJson(not)
        op.setType(MultipartBody.FORM)
            .addFormDataPart("body", jsonInString).build()
        //val requestBody = op.build()

        val requestBody = RequestBody.create(MediaType.parse("text/plain"), jsonInString)


@Headers("Content-Type: application/json")
    @POST("addNotification")
    fun addNotification(@Body not: RequestBody) : Call<Status>
json swift alamofire
1个回答
0
投票

如果您想发布json,可以这样:

let parameters = ["name": "John", "age": 30]

        AF.request(urlString, headers: headers, parameters: parameters).response { response in
        print(response)
     } 

您可以使用字典。

© www.soinside.com 2019 - 2024. All rights reserved.