通过Alamofire发送json数组

fru*_*sli 58 swift alamofire

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

[
    "06786984572365",
    "06644857247565",
    "06649998782227"
]
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 134

您可以只使用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)
        }
}
Run Code Online (Sandbox Code Playgroud)

对于Swift 2,请参阅此答案的先前版本.


man*_*eGE 51

对于swift 3和Alamofire 4,我使用以下ParametersEncodingArray扩展名:

import Foundation
import Alamofire

private let arrayParametersKey = "arrayParametersKey"

/// Extenstion that allows an array be sent as a request parameters
extension Array {
    /// Convert the receiver array to a `Parameters` object. 
    func asParameters() -> Parameters {
        return [arrayParametersKey: self]
    }
}


/// Convert the parameters into a json array, and it is added as the request body. 
/// The array must be sent as parameters using its `asParameters` method.
public struct ArrayEncoding: ParameterEncoding {

    /// The options for writing the parameters as JSON data.
    public let options: JSONSerialization.WritingOptions


    /// Creates a new instance of the encoding using the given options
    ///
    /// - parameter options: The options used to encode the json. Default is `[]`
    ///
    /// - returns: The new instance
    public init(options: JSONSerialization.WritingOptions = []) {
        self.options = options
    }

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        guard let parameters = parameters,
            let array = parameters[arrayParametersKey] else {
                return urlRequest
        }

        do {
            let data = try JSONSerialization.data(withJSONObject: array, options: options)

            if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
                urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
            }

            urlRequest.httpBody = data

        } catch {
            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
        }

        return urlRequest
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,它将数组转换为a Dictionary以便被接受为Parameters参数,然后它从字典中获取数组,将其转换为JSON Data并将其添加为请求主体.

获得后,您可以通过以下方式创建请求:

let values = ["06786984572365", "06644857247565", "06649998782227"]
Alamofire.request(url,
                  method: .post,
                  parameters: values.asParameters(),
                  encoding: ArrayEncoding())
Run Code Online (Sandbox Code Playgroud)