[英]Post Json string in Alamofire
How to post a json string using Alamofire. 如何使用Alamofire发布json字符串。 Alamofire request takes only Dictionary type as parameter:
[String : Any]
. Alamofire请求仅将Dictionary类型作为参数:
[String : Any]
。 But I want to pass a json string as a parameter, not Dictionary. 但是我想传递一个json字符串作为参数,而不是Dictionary。
Alamofire.request(url, method: .post,
parameters: [String : Any], // <-- takes dictionary !!
encoding: JSONEncoding.default, headers: [:])
您正在使用encoding: JSONEncoding.default
的形式和您的参数数据[String : Any]
当你传递数据Alamofire编码您[String : Any]
以json
becuse你已经提到你的编码方法将JSONEncoding.default
服务器将接收编码的JSON
The easiest way is to convert your json data to native dictionary and use it as intended: 最简单的方法是将json数据转换为本机字典并按预期使用它:
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: [:])
duplicate: POST request with a simple string in body with Alamofire 重复: 带有Alamofire正文的简单字符串的POST请求
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: [:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.