【问题标题】:Post Json string in Alamofire在 Alamofire 中发布 Json 字符串
【发布时间】:2018-05-08 03:05:14
【问题描述】:

如何使用 Alamofire 发布 json 字符串。 Alamofire 请求仅将 Dictionary 类型作为参数:[String : Any]。但我想传递一个 json 字符串作为参数,而不是 Dictionary。

Alamofire.request(url, method: .post, 
         parameters: [String : Any], // <-- takes dictionary !!
         encoding: JSONEncoding.default, headers: [:])

【问题讨论】:

  • 你解决了这个问题吗?

标签: ios swift alamofire


【解决方案1】:

最简单的方法是将您的 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]
}

用法:

var params = jsonToDictionary(from: json) ?? [String : Any]()
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:])

【讨论】:

    【解决方案2】:

    您正在使用encoding: JSONEncoding.default[String : Any] 形式的参数数据,同时您将数据Alamofire 编码您的[String : Any]json 因为您已经提到您的编码方法将是JSONEncoding.default 服务器将接收编码JSON

    【讨论】:

    • 这不是 OP 所追求的;他想传递一个字符串而不是一个字典。 E.g.: "This is a string", BUT ["this is" : "dictionary"]
    【解决方案3】:

    重复: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: [:])
    

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 2016-02-04
      • 2019-04-23
      • 2017-03-13
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多