Alamofire 5 转义正斜杠

Tom*_*Tom 1 swift alamofire

在过去的几天里,我一直在谷歌搜索并尝试关于 alamofire 的正斜杠的自动转义。

(其中“/path/image.png”变成 "\/path\/image.png")

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

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

我没有使用 SwiftyJson 并且觉得安装 API 只是为了解决这个问题是一个用大锤敲钉子的情况。

反正。

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

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

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
Run Code Online (Sandbox Code Playgroud)

}

也许创建一个自定义的 json 编码器是这样做的方法,但我发现关于如何最好地去做的文档很少。

我也试过

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.
Run Code Online (Sandbox Code Playgroud)

我什至读到后端应该能够处理转义字符,但它对 android 开发人员来说工作正常。因此,如果我的代码发送了错误的数据,那么我觉得它应该在源头解决

托马斯

csi*_*sim 6

我遇到了同样的问题,并决定采用自定义 JSON 编码器的方式。可能有比这更好/更短的方法,但鉴于我是一个 Swift 菜鸟,它可以完成它的工作并且对我来说已经足够了。

我只是查找了 Alamofire 使用的使用过的 JSONEncoder 并制作了我自己的:

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
}
}
Run Code Online (Sandbox Code Playgroud)

可能还应该包括更多的错误处理:)

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

Alamofire.request(EndpointsUtility.sharedInstance.cdrStoreURL, method: .post, parameters: payload, encoding: JSONEncodingWithoutEscapingSlashes.prettyPrinted)...
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!