如何在Swift3中将总模型对象作为Alamofire post方法的参数发送? [英] How to send total model object as a parameter of Alamofire post method in Swift3?
问题描述
我有一个像这样的模型课
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"
之后,我转换为JSON,然后发布了
After that I converted to JSON then I posted
Alamofire.request(URL, method:.post, parameters: example)
Alamofire仅接受其接受的参数,例如parameters = ["":"","",""]-->key value based
,所以我尝试将模型转换为JSON,将JSON转换为字典,即使不接受其显示参数的问题.确实我需要像这样在Alamofire中将总模型对象作为post方法的参数发送:
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)
推荐答案
由于Alamofire API仅接受字典,因此请自己创建字典!
Since the Alamofire API is only accepting dictionaries, create a dictionary yourself!
在模型类中添加一个名为toJSON
的方法:
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
]
}
然后在调用request
时调用此方法:
Then call this method when calling request
:
Alamofire.request(URL,
method:.put,
parameters:example.toJSON(),
encoding:JSONEncoding.default,
headers :Defines.Api.Headers )
或者,使用SwiftyJSON:
Alternatively, use SwiftyJSON:
func toJSON() -> JSON {
return [
"name": name as Any,
"age": age as Any,
"marks": marks as Any
]
}
用法:
Alamofire.request(URL,
method:.put,
parameters:example.toJSON().dictionaryObject,
encoding:JSONEncoding.default,
headers :Defines.Api.Headers )
这篇关于如何在Swift3中将总模型对象作为Alamofire post方法的参数发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!