How to send total model object as a parameter of Alamofire post method in Swift3?

那年仲夏 提交于 2020-01-22 14:51:10

问题


I have a model class like this

class Example() {
  var name:String?
  var age:String?
  var marks:String? 
}

I'm adding data to that model class

let example = Example()
example.name = "ABC"
example.age = "10"
example.marks = "10" 

After that I converted to JSON then I posted

Alamofire.request(URL, method:.post, parameters: example)

Alamofire not accepting parameters only its accepting like parameters = ["":"","",""]-->key value based, so I tried to convert model to JSON, JSON to dictionary, even though not accepting its showing like parameters problem. Exactly I need total model object need to send as a parameter of post method in Alamofire like this:

let example = Example()
Alamofire.request(URL, method:.post, parameters: example) 

回答1:


Since the Alamofire API is only accepting dictionaries, create a dictionary yourself!

Add a method in the model class called toJSON:

func toJSON() -> [String: Any] {
    return [
        "name": name as Any,
        "age": age as Any,
        "marks": marks as Any
    ]
}

Then call this method when calling request:

Alamofire.request(URL, 
    method:.put, 
    parameters:example.toJSON(), 
    encoding:JSONEncoding.default, 
    headers :Defines.Api.Headers )

Alternatively, use SwiftyJSON:

func toJSON() -> JSON {
    return [
        "name": name as Any,
        "age": age as Any,
        "marks": marks as Any
    ]
}

Usage:

Alamofire.request(URL, 
    method:.put, 
    parameters:example.toJSON().dictionaryObject, 
    encoding:JSONEncoding.default, 
    headers :Defines.Api.Headers )



回答2:


The best way so far is to make your model conform to Encodable then convert you model into json Data like so

let data = try! JSONEncoder.init().encode(example)

then use SwiftyJSON to convert it back to dictionary

let json = try! JSON.init(data: data)
let dictionary = json.dictionaryObject

as Rob said you can also use JSONSerialization if you are not already using SwiftyJSON

let dictionary = try! JSONSerialization.jsonObject(with: data) as! [String: Any]

Then use the dictionary in your parameters

Also Alamofire now supports Encodable parameters with

let urlRequest = JSONParameterEncoder.init().encode(example, into: urlRequest)


来源:https://stackoverflow.com/questions/43649027/how-to-send-total-model-object-as-a-parameter-of-alamofire-post-method-in-swift3

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