[SalesForce] JSON Serialize and Deserialize on HttpRequest

In order to make a @future(callout=true) call, I'm serializing an HTTPRequest object in order to send it to the @future method accepting a String jsonHttpRequest parameter.

Instance Method

HttpRequest request = new HttpRequest();

request.setEndpoint(someUrl);
// ... continue populating request

sendAsyncRequest(JSON.serialize(request));

Future Method

@future(callout=true)
private static void sendAsyncRequest(String jsonHttpRequest) {
    HttpResponse response = new Http().send((HttpRequest)JSON.deserialize(jsonHttpRequest, HttpRequest.class));
}

But this code is giving me the following error:

System.JSONException: Apex Type unsupported in JSON: System.HttpRequest

Using JSON.deserializeStrict() and JSON.deserializeUntyped() hasn't worked for me either.

Any ideas here? I'm open to other approaches (thought about Queueable but @future is a more natural fit for the current use case)

Best Answer

There are certain classes that are not serializable, and HttpRequest is one of them. I can't seem to find supporting documentation, but from what I recall this is a pretty common constraint in other languages too.

The solution here is to store the configuration for your callout in something like a Map<String, String> or a custom configuration wrapper class, serialize that, and then use it to create your HttpRequest inside of your async method of choice.

If you go the route of the configuration wrapper class, you could include a method that returns an HttpRequest to save you the trouble of doing it elsewhere.

Related Topic