Alamofire 5转义斜线 [英] Alamofire 5 Escaping Forward Slashes

查看:145
本文介绍了Alamofire 5转义斜线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几天里,我一直在搜寻有关Alamofire正斜杠的自动转义的尝试。

Ive been googling and trying for the last few days regarding the automatic escaping of forward slashes of alamofire.

(其中 /path/image.png变为 \ / path\ / image.png)

(Where "/path/image.png" becomes "\/path\/image.png")

但是,如果您使用swiftyJson,通过httpBody发送或使用Alamofire参数类,则所有答案都指向解决方案。

However all the answers either point towards a solution if your using swiftyJson, sending via a httpBody or using the Alamofire Parameter Class.

https://github.com/SwiftyJSON/SwiftyJSON/issues/440

我不使用SwiftyJson并觉得安装API只是为了解决问题,是用大铁锤砸钉子的情况。

Im not using SwiftyJson and feel to install the API just to resolve the issue is a case of hitting the nail with a sledge hammer.

无论如何。

我的问题是,每当我尝试向API发送参数时,Alamofire的
JSONEncoding.default都会转义正斜线。我不希望Alamofire这样做。

My issue is whenever I'm trying to send parameters to an API, Alamofire's JSONEncoding.default kindly escapes forward slashes. I don't want Alamofire to do this.

在我的情况下,我想发送以下参数并使Alamofire忽略正斜杠

In my case I want to send the following parameter and have Alamofire ignore the forward slashes

let parameter : Parameters =  ["transaction": "/room/120"] 

Alamofire.request(endPoint , method: .post, parameters: parameter ,encoding: JSONEncoding.default , headers: header).validate(statusCode: 200..<300).responseObject { (response: DataResponse<SomeModel>) in

}

也许创建自定义json编码器是实现此目的的方法,但我发现

Maybe creating a custom json encoder is the way to do this but I find very little documentation on how best to go about it.

我也尝试过

let parameter : [String : Any] =  ["transaction": "/room/120"] 

Alamofire.request(endPoint , method: .post, parameters: parameter ,encoding: JSONEncoding.default , headers: header).validate(statusCode: 200..<300).responseObject { (response: DataResponse<SomeModel>) in
Really appreciate all your help and suggestions.

我什至读过后端应该能够处理转义字符,但是对于Android开发人员因此,如果我的代码发送了错误的数据,那么我认为应该在源代码处解决

Ive even read that the backend should be able to deal with the escaping characters, but its working fine for the android dev. Thus if its my code that is sending the wrong data, then I feel it should resolved at the source

Thomas

推荐答案

我遇到了同样的问题,因此决定采用自定义JSON编码器的方式。可能有比这更好/更短的方法,但是看到我是一个Swift菜鸟,它确实起作用并且对我来说足够好。

I had the same issue and decided to go the way of the custom JSON encoder. There are probably better/shorter ways than this but seeing as I'm a Swift noob, it does it's job and is good enough for me.

我只是抬头看了一下使用Alamofire使用的JSONEncoder并自己制作:

I simply looked up the used JSONEncoder used by Alamofire and made my own:

public struct JSONEncodingWithoutEscapingSlashes: ParameterEncoding {

// MARK: Properties

/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncodingWithoutEscapingSlashes { return JSONEncodingWithoutEscapingSlashes() }

/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncodingWithoutEscapingSlashes { return JSONEncodingWithoutEscapingSlashes(options: .prettyPrinted) }

/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions

// MARK: Initialization

/// Creates a `JSONEncoding` instance using the specified options.
///
/// - parameter options: The options for writing the parameters as JSON data.
///
/// - returns: The new `JSONEncoding` instance.
public init(options: JSONSerialization.WritingOptions = []) {
    self.options = options
}

// MARK: Encoding

/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    var urlRequest = try urlRequest.asURLRequest()

    guard let parameters = parameters else { return urlRequest }

    do {
        let data = try JSONSerialization.data(withJSONObject: parameters, options: options)

        let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)?.replacingOccurrences(of: "\\/", with: "/")

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = string!.data(using: .utf8)
    } catch {
        throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
    }

    return urlRequest
}

/// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
///
/// - parameter urlRequest: The request to apply the JSON object to.
/// - parameter jsonObject: The JSON object to apply to the request.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
    var urlRequest = try urlRequest.asURLRequest()

    guard let jsonObject = jsonObject else { return urlRequest }

    do {
        let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)

        let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)?.replacingOccurrences(of: "\\/", with: "/")

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = string!.data(using: .utf8)
    } catch {
        throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
    }

    return urlRequest
}
}

可能也应该包含更多错误处理:)

Probably should include some more error handling too :)

最后,我可以像标准JSONEncoder一样使用它:

Finally I could use it like the standard JSONEncoder:

Alamofire.request(EndpointsUtility.sharedInstance.cdrStoreURL, method: .post, parameters: payload, encoding: JSONEncodingWithoutEscapingSlashes.prettyPrinted)...

希望有帮助!

这篇关于Alamofire 5转义斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆