swift - 数组作为参数不适用于 Alamofire

标签 swift alamofire http-status-code-500

我有一个 API,我需要将数据作为对象发送,因此我按如下方式传递数据,它工作正常。

["fname" : "First 1", "lname": "Last 1"]

但对于其中一个 API,Web 开发人员需要 API 作为数组,如下所示。

[["fname" : "First 1", "lname": "Last 1"]]

知道出了什么问题吗?

下面是我的代码

parameters = ..... data that I passed as [String : Any] // e.x. ["fname" : "First 1", "lname": "Last 1"]

var finalWebParams : Any

var webParams2 : [[String : Any]] = [[String : Any]]()
if (webserviceFor=="array") {
    webParams = parameters as [String:Any]
    webParams2.append(webParams)
}

if (webserviceFor=="array") {
    finalWebParams = webParams2
} else {
    finalWebParams = webParams
}

print("finalWebParams==\(finalWebParams)")

request(url, method: webMethod, parameters: finalWebParams as? Parameters, encoding: myEncoding, headers: headers)

对于print,我得到的结果如下,意味着我传递了正确的数据,但出现了 500 错误。

[["fname" : "First 1", "lname": "Last 1"]]

知道我做错了什么吗?

<小时/>

编辑 1

以下是Web开发人员需要的模型

[
    {
        "fname" : "First 1",
        "lname" : "Last 1"
    }
]

最佳答案

答案是我需要添加 ArrayEncoding,如下所示。

var finalWebParams : [String : Any]

var webParams2 : [[String : Any]] = [[String : Any]]()
if (webserviceFor=="array") {
    webParams = parameters as [String:Any]
    webParams2.append(webParams)
}

if (webserviceFor=="array") {
    finalWebParams = webParams2.asParameters()
} else {
    finalWebParams = webParams
}

现在添加扩展

private let arrayParametersKey = "arrayParametersKey"

/// Extenstion that allows an array be sent as a request parameters
extension Array {
    /// Convert the receiver array to a `Parameters` object.
    func asParameters() -> Parameters {
        return [arrayParametersKey: self]
    }
}


/// Convert the parameters into a json array, and it is added as the request body.
/// The array must be sent as parameters using its `asParameters` method.
struct ArrayEncoding: ParameterEncoding {

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


    /// Creates a new instance of the encoding using the given options
    ///
    /// - parameter options: The options used to encode the json. Default is `[]`
    ///
    /// - returns: The new instance
    public init(options: JSONSerialization.WritingOptions = []) {
        self.options = options
    }

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        guard let parameters = parameters,
            let array = parameters[arrayParametersKey] else {
                return urlRequest
        }

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

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

            urlRequest.httpBody = data

        } catch {
            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
        }

        return urlRequest
    }
}

关于swift - 数组作为参数不适用于 Alamofire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53021210/

相关文章:

swift - WidgetKit getCurrentConfigurations 返回错误的 WidgetKit 配置列表

ios - 如何将变量的值设置为从 Alamofire 收到的数据?

swift - 使用 Alamofire 和 Objectmapper 整数值始终为零

C# Bot Framework 和最大上传限制

azure - 虚拟目录部署的内部错误

ios - 添加和删​​除 NSNotificationCenter Observer - UIApplicationDidEnterBackgroundNotification - 正确的方法?

xcode - 在 Swift 中返回一个未包装的可选?

ios - 关闭模态视图但保留数据

ios - Alamofire+组合 : how to get custom error type out of AFError

node.js - NODE ACL 模块生成 500 而不是 403