2

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.

3
  • What is JSON in let address: JSON? Commented Dec 23, 2016 at 4:52
  • @Mr.Bista I'm using SwiftyJSON. JSON is a data type. Commented Dec 27, 2016 at 20:38
  • were u able to resolve the issue? Commented Dec 28, 2016 at 15:54

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.