Reputation: 149
How to post a json string using Alamofire. Alamofire request takes only Dictionary type as parameter: [String : Any]
. But I want to pass a json string as a parameter, not Dictionary.
Alamofire.request(url, method: .post,
parameters: [String : Any], // <-- takes dictionary !!
encoding: JSONEncoding.default, headers: [:])
Upvotes: 2
Views: 6132
Reputation: 402
duplicate:POST request with a simple string in body with Alamofire
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
Upvotes: 0
Reputation: 6058
The easiest way is to convert your json data to native dictionary and use it as intended:
func jsonToDictionary(from text: String) -> [String: Any]? {
guard let data = text.data(using: .utf8) else { return nil }
let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: Any]
}
Usage:
var params = jsonToDictionary(from: json) ?? [String : Any]()
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:])
Upvotes: 1
Reputation: 2139
You are using encoding: JSONEncoding.default
and your parameter data in the form of [String : Any]
while you passing the data Alamofire encode your [String : Any]
to json
becuse you already mentioned your encoding method will be JSONEncoding.default
server will receive encoded JSON
Upvotes: 0