gpt4 book ai didi

swift - Alamofire 5 转义正斜杠

转载 作者:搜寻专家 更新时间:2023-11-01 06:14:59 24 4
gpt4 key购买 nike

过去几天我一直在谷歌搜索并尝试有关自动转义 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

也许创建自定义 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.

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

托马斯

最佳答案

我遇到了同样的问题,决定采用自定义 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
}
}

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

我终于可以像使用标准 JSONEncoder 一样使用它了:

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

希望对您有所帮助!

关于swift - Alamofire 5 转义正斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47267192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com