tristanhimmelman/AlamofireObjectMapper

Question about passing mapping to POST, PATCH, and PUT requests.

Closed this issue · 4 comments

Hi,

I have a question about doing POST, PATCH, and PUT requests when using Alamofire and AlamofireObjectMapper. For example, lets say that I am doing a POST request to to send a object to a server. Can I pass a mapping as parameters for the request. Does it work similar to how Restkit encodes parameters into the body of the request as JSON?

You can use toJSON(): (example in Swift 3 with Alamofire 4.0)

let parameters: Parameters = yourMappableObject.toJSON()
_ = Alamofire.request(theURL, method:.post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON() { ... }

The BaseMappable.toJSON returns a [String: Any] which is exactly what Parameters is (Alamofire.Parameters source):

public typealias Parameters = [String : Any]

You must use JSONEncoding which will use your JSON dictionary as the httpBody (as per the doc Alamofire.JSONEncoding):

/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
public struct JSONEncoding : ParameterEncoding {
...

Now can you provide different methods for toJSON() or only one is allowed?

Thanks @stefanhp

@eman6576 I don't understand your follow question. I am going to close this until you response as your initial question was answered.

@tristanhimmelman I think what I mean is can I have a toJSON() for just doing POST requests and one toJSON() for PATCH requests for one model class or is the toJSON() method meant to be generic meaning it can only be implemented once?