过去几天我一直在谷歌搜索并尝试有关 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)...
希望有帮助!
您可以使用选项创建 JSONEncoding:
let encoding: ParameterEncoding = JSONEncoding(options: [.withoutEscapingSlashes])
使用此编码而不是 JSONEncoding.default