迁移编码:.Custom(marshal)

时间:2017-04-16 22:14:47

标签: swift3 alamofire

因为我需要从类型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)编译,但似乎无法正常工作。

编辑:没关系它的工作:)做了别的愚蠢与此无关,我会留在这里帮助其他人。如果您有更好的解决方案,请随意回答。

1 个答案:

答案 0 :(得分:0)

假设你的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
            }
        }