Alamofire Post Request with nested JSON parameters

牧云@^-^@ 提交于 2019-12-24 09:42:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!