问题
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"
]
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
]
The Alamofire request is not performed and my application crashes.
回答1:
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.
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
回答2:
For those not using SwiftyJSON, the Parameters type accepts a Parameters type as well, like so:
let address: Parameters = [
"street": "1234 Fake St",
"city": "Seattle",
"state": "WA"
]
let parameters: Parameters = [
"firstName": "John",
"lastName": "Doe",
"address": address
]
来源:https://stackoverflow.com/questions/41294012/alamofire-post-request-with-nested-json-parameters