简体   繁体   中英

Alamofire request with SwiftyJSON parameters

I would like to know how I can put a SwiftyJSON array into my parameters for the Alamofire request.

Actually I use this code (Swift 3) to setup the parameters for the request:

let params = ["customObjects": customObjects.map({$0.toJSON()})]

...but this fires an exception if I try to start the request:

uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

The "customObjects" are an array of my custom model class.

If you need any more information let me know.

You can convert a SwiftyJSON object (called yourJSON here) to parameters like so:

let parameters : Parameters = yourJSON.dictionaryObject ?? [:]

Then you can use it in an Alamofire request like so:

Alamofire.request("https://yourURL.com/somePath", method: .post, parameters: parameters, encoding:  JSONEncoding.default, headers: nil).responseJSON { response in
   // ... do whatever you would like with the response 
}

I found the solution by myself:

let params = ["customObjects": customObjects.map({$0.toDictionary()})]

And here the toDictionary() func inside my CustomObject:

func toDictionary() -> [String: Any] {
    let dict: [String: Any] = [
        "exampleKey": "exampleValue",
        "exampleKey2": "exampleValue2"
    ]

    return dict
}

I guess this is because you can setup Alamofire with encoding: JSONEncoding.default .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM