通过 Alamofire 发送 json 数组 [英] Sending json array via Alamofire

查看:47
本文介绍了通过 Alamofire 发送 json 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 POST 请求中直接发送一个数组(不包含在字典中).显然 parameters 参数应该得到一个映射:[String: AnyObject]?但我希望能够发送以下示例 json:

<预><代码>["06786984572365","06644857247565",06649998782227"]

解决方案

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

var request = URLRequest(url: url)request.httpMethod = "POST";request.setValue("application/json", forHTTPHeaderField: "Content-Type")让值 = [06786984572365"、06644857247565"、06649998782227"]request.httpBody = 试试!JSONSerialization.data(withJSONObject: values)AF.request(request)//或者 Alamofire 之前版本中的 `Alamofire.request(request)`.responseJSON { 响应输入切换 response.result {案例.失败(让错误):打印(错误)if let data = response.data, let responseString = String(data: data, encoding: .utf8) {打印(响应字符串)}案例.成功(让响应对象):打印(响应对象)}}

对于 Swift 2,请参阅此答案的以前的修订版.

I wonder if it's possible to directly send an array (not wrapped in a dictionary) in a POST request. Apparently the parameters parameter should get a map of: [String: AnyObject]? But I want to be able to send the following example json:

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

解决方案

You can just encode the JSON with NSJSONSerialization and then build the NSURLRequest yourself. For example, in 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)

AF.request(request)                               // Or `Alamofire.request(request)` in prior versions of Alamofire
    .responseJSON { response in
        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)
        }
}

For Swift 2, see previous revision of this answer.

这篇关于通过 Alamofire 发送 json 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆