Alamofire Post Request with nested JSON parameters

2.9k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

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
]