一尘不染

通过Alamofire发送json数组

swift

我想知道是否可以在POST请求中直接发送一个数组(未包装在字典中)。显然,该parameters参数应获取以下内容的映射:[String:AnyObject]?但我希望能够发送以下示例json:

[
    "06786984572365",
    "06644857247565",
    "06649998782227"
]

阅读 493

收藏
2020-07-07

共1个答案

一尘不染

您可以使用JSON进行编码NSJSONSerialization,然后自行构建NSURLRequest。例如,在Swift 3中:

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let values = ["06786984572365", "06644857247565", "06649998782227"]

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

Alamofire.request(request)
    .responseJSON { response in
        // do whatever you want here
        switch response.result {
        case .failure(let error):
            print(error)

            if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
                print(responseString)
            }
        case .success(let responseObject):
            print(responseObject)
        }
}
2020-07-07