带有嵌套JSON参数的Alamofire发布请求 [英] Alamofire Post Request with nested JSON parameters
问题描述
我的Alamofire发布请求如下所示:
My Alamofire post request looks like this:
Alamofire.request("http://...", method: HTTPMethod.post, parameters: parameters, encoding: JSONEncoding.default, headers: nil)
.responseJSON(completionHandler: {(response) in ... })
如果我的参数很简单,那么一切都很好:
Everything works fine if my parameters are simple:
let parameters: Parameters = [
"firstName": "John",
"lastName": "Doe"
]
如果我的参数包含json对象,则会遇到问题。
I run into problems if my parameters contain a json object.
let address: JSON = [
"street": "1234 Fake St",
"city": "Seattle",
"state": "WA"
]
let parameters: Parameters = [
"firstName": "John",
"lastName": "Doe",
"address": address
]
Alamofire请求未执行,我的应用程序崩溃了。
The Alamofire request is not performed and my application crashes.
推荐答案
我相信e这里的问题是Alamofire试图将参数编码为已经是json对象的json。本质上,双重编码会导致应用程序崩溃。
I believe the issue here is that Alamofire is trying to encode a parameter as json that is already a json object. Essentially, double-encoding causes the application to crash.
我发现的解决方案是在使用SwiftyJSON的 .rawValue执行请求之前解码json参数。
。
The solution I found was to decode the json parameter before performing the request using SwiftyJSON's .rawValue
.
let parameters: Parameters = [
"firstName": "John",
"lastName": "Doe",
"address": address.rawValue
]
https://github.com/SwiftyJSON/SwiftyJSON#raw-object
这篇关于带有嵌套JSON参数的Alamofire发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!