【问题标题】:migration encoding:.Custom(marshal)迁移编码:.Custom(元帅)
【发布时间】:2017-04-16 22:14:46
【问题描述】:

因为我需要从 Array<Array<Double>> 而不是 Dictionary<String, Any> 类型创建一个 json 字符串,所以我需要自定义编码并且不能使用 alamofire 4 中的默认 json 编码。

在 alamofire 3 中我这样做了:

    let marshal: (URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) = {
        (urlRequest, parameters) in
        var mutableURLRequest = urlRequest as! NSMutableURLRequest
        mutableURLRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.httpBody = self.buffer.json()
        return (mutableURLRequest, nil)
    }

但我对 swift 3 的了解不够,无法理解我应该如何实现可以在 alamofire 4 中使用的编码协议

https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol

您能否提供一个实现 alamofire 4 编码协议的示例。

基于https://github.com/Alamofire/Alamofire#custom-encoding我试过了:

    struct JSONStringArrayEncoding: ParameterEncoding {
        private let buffer: Array<Array<Double>>
        init(_ buffer: Array<Array<Double>>) {
            self.buffer = buffer
        }
        func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var urlRequest = try urlRequest.asURLRequest()
            urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            urlRequest.httpBody = self.buffer.json()
            return urlRequest
        }
    }

encoding:JSONStringArrayEncoding(self.buffer) 编译但似乎不起作用。

编辑:没关系它的工作原理:) 做了一些与此无关的愚蠢行为,我将把它留在这里帮助其他人。如果您有比上述更好的解决方案,请随时回答。

【问题讨论】:

    标签: swift3 alamofire


    【解决方案1】:

    假设你的 json 字符串是:- {"action":"userLogin","info":{"email":"chandragirish86@gmail.com","password":"qwert123","login":"login"}} 那么你应该在下面写字典:-

    let jsonObject: [String: Any] = ["action":Urls.loginUrl,
                                             "info":["email":"chandragirish86@gmail.com","password":"qwert123","login":"login"]]
    

    然后你只需调用带有json编码的Alamofire post函数:-

    Alamofire.request (url, method: .post, parameters: jsonObject,encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
                switch(response.result) {
                case .success(_):
                    if let data = response.data{
    
                        let json:JSON = JSON(data: data)
                        completionHandler(json,nil)
                    }
                    break
                case .failure(_):
                    print("URL> \(url)...\(response.result.error as Any)")
                    completionHandler(nil,response.result.error as NSError?)
                    break
                }
            }
    

    【讨论】:

    • 这只是默认的 json 解决方案,甚至不使用自定义编码或 Array> 作为输入
    • 如果您想将任何对象转换为 json(如果有效),那么只需使用 do { let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted) // here "jsonData" is the dictionary encoded in JSON data let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) // here "decoded" is of type Any, decoded from JSON data // you can now cast it with the right type if let dictFromJSON = decoded as? [String:String] { // use dictFromJSON } } catch { print(error.localizedDescription) }
    • 也许是这样,但这就是encoding: 的用途,我的问题是具体如何使用alamofire 4 编码协议。我看不出这个答案如何适合这个问题。
    最近更新 更多