Alamofire: Send JSON with Array of Dictionaries

Viewed 12044

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     
        }
    }
3 Answers
Related