Search code examples
jsonserializationalamofire

Assign directly to the request body when POST-ing


I would like to assign some JSON text to the request body of a POST request and not have any variables. So, instead of this as the request body, for example...

myVal={"hello"="world"}

I would like this...

{"hello"="world"}

Is this possible?


Solution

  • I created a custom parameter encoding...

    import Alamofire
    
    struct JsonParameterEncoding: ParameterEncoding {
    
        private let jsonString: String
    
        init(jsonString: String) {
    
            self.jsonString = jsonString
        }
    
        func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    
            var urlRequest = urlRequest.urlRequest!
    
            if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
    
                urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
            }
    
            urlRequest.httpBody = jsonString.data(using: .utf8)
    
            return urlRequest
        }
    }