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 cla
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)
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 )