Alamofire: Send JSON with Array of Dictionaries

前端 未结 3 1435
一整个雨季
一整个雨季 2020-12-10 08:04

I have a data structure that looks like this in JSON:

[{
    \"value\": \"1\",
    \"optionId\": \"be69fa23-6eca-4e1b-8c78-c01daaa43c88\"
}, {
    \"value\":         


        
3条回答
  •  时光取名叫无心
    2020-12-10 08:44

    I have the same issue and resolved this way:

    I created a new struct implementing the Alamofire's ParameterEncoding protocol:

    struct JSONArrayEncoding: ParameterEncoding {
        private let array: [Parameters]
    
        init(array: [Parameters]) {
            self.array = array
        }
    
        func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var urlRequest = try urlRequest.asURLRequest()
    
            let data = try JSONSerialization.data(withJSONObject: array, options: [])
    
            if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
                urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
            }
    
            urlRequest.httpBody = data
    
            return urlRequest
        }
    }
    

    Then, I can do this:

    let parameters : [Parameters] = bodies.map( { $0.bodyDictionary() })
    Alamofire.request(url, method: .post, encoding: JSONArrayEncoding(array: parameters), headers: headers).responseArray { ... }
    

    It worked for me. Hope can help someone else.

提交回复
热议问题