Alamofire: Send JSON with an 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"
}]

This is mainly an array of dictionaries. I would prefer to use standard Alamofire methods and would not want to create a query manually. Is there a way to give Alamofire my options and Alamofire will do the rest?

If I create everything manually, I get an error from the server that the send data will be incorrect.

    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     
        }
    }
+4
source share
3 answers

You can do something like this:

Alamofire.request(.POST, urlPath, parameters: params).responseJSON{ request, response, data in
    //YOUR_CODE
}

Where parametersthere is [String:AnyObject], and yes Alamofire takes care of the rest.

Since it looks like you are using a manager, you can do it

YOUR_ALAMOFIRE_MANAGER.request(.POST, url, parameters: params).responseJSON{ request, response, JSON in
   //enter code here
}

Here is the source code:

public func request(
    method: Method,
    _ URLString: URLStringConvertible,
    parameters: [String: AnyObject]? = nil,
    encoding: ParameterEncoding = .URL,
    headers: [String: String]? = nil)
    -> Request
{
    let mutableURLRequest = URLRequest(method, URLString, headers: headers)
    let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
    return request(encodedURLRequest)
}

EDIT:

[[String:AnyObject]], , [String:AnyObject]. , ["data":[[String:AnyObject]]]. , api.

-2

:

, Alamofire ParameterEncoding :

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
    }
}

:

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

. - .

+6

JSON POST, JSON .

Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)

This is described in the ReadMe Alamofire github file - https://github.com/Alamofire/Alamofire#post-request-with-json-encoded-parameters

let parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ]
]

Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
-1
source

All Articles