[英]Alamofire request with SwiftyJSON parameters
I would like to know how I can put a SwiftyJSON array into my parameters for the Alamofire request.我想知道如何将 SwiftyJSON 数组放入 Alamofire 请求的参数中。
Actually I use this code (Swift 3) to setup the parameters for the request:实际上我使用此代码(Swift 3)来设置请求的参数:
let params = ["customObjects": customObjects.map({$0.toJSON()})]
...but this fires an exception if I try to start the request: ...但是如果我尝试启动请求,这会引发异常:
uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
The "customObjects" are an array of my custom model class. “customObjects”是我的自定义模型类的数组。
If you need any more information let me know.如果您需要更多信息,请告诉我。
You can convert a SwiftyJSON object (called yourJSON
here) to parameters like so:您可以将 SwiftyJSON 对象(此处称为yourJSON
)转换为如下参数:
let parameters : Parameters = yourJSON.dictionaryObject ?? [:]
Then you can use it in an Alamofire request like so:然后你可以在 Alamofire 请求中使用它,如下所示:
Alamofire.request("https://yourURL.com/somePath", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
// ... do whatever you would like with the response
}
I found the solution by myself:我自己找到了解决方案:
let params = ["customObjects": customObjects.map({$0.toDictionary()})]
And here the toDictionary() func inside my CustomObject:这里是我的 CustomObject 中的 toDictionary() 函数:
func toDictionary() -> [String: Any] {
let dict: [String: Any] = [
"exampleKey": "exampleValue",
"exampleKey2": "exampleValue2"
]
return dict
}
I guess this is because you can setup Alamofire with encoding: JSONEncoding.default
.我想这是因为您可以使用encoding: JSONEncoding.default
设置 Alamofire encoding: JSONEncoding.default
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.