Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire: Send JSON with Array of Dictionaries

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

[{
    "value": "1",
    "optionId": "be69fa23-6eca-4e1b-8c78-c01daaa43c88"
}, {
    "value": "0",
    "optionId": "f75da6a9-a34c-4ff6-8070-0d27792073df"
}]

Basically it is an array of dictionaries. I would prefer to use the default Alamofire methods and would not like to build the request manually. Is there a way to give Alamofire my parameters and Alamofire does the rest?

If I create everything by hand I get an error from the server that the send data would not be correct.

    var parameters = [[String:AnyObject]]()

    for votingOption in votingOptions{

        let type = votingOption.votingHeaders.first?.type

        let parameter = ["optionId":votingOption.optionID,
            "value": votingOption.votingBoolValue
        ]
        parameters.append(parameter)
    }

    let jsonData = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
    let json = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments)


    if let url = NSURL(string:"myprivateurl"){
        let request = NSMutableURLRequest(URL: url)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = Method.POST.rawValue
        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

        AlamofireManager.Configured.request(request)
            .responseJSON { response in
           //Handle result     
        }
    }
like image 232
netshark1000 Avatar asked Mar 24 '16 15:03

netshark1000


1 Answers

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.

like image 95
jorgifumi Avatar answered Nov 20 '22 07:11

jorgifumi