[SalesForce] JSON.serialize Url object throwing System.JSONException

I'm getting the following JSONException when JSON serializing a Map of generic Objects which contains a Url object deeply nested within.

System.JSONException: Type unsupported in JSON: common.apex.methods.ApexUrl$URIImpl

It looks like Apex doesn't support JSON serializing the Url class because I was able to replicate the error in Anonymous Apex simply with JSON.serialize(new Url('https://www.google.com'));.

What would be the best way to serialize my object without having to refactor my Url properties to String? For some context, I'm serializing the Map described in this question.

Best Answer

You'll have to do some refactoring, but this is a pretty clean solution:

public class DataHandler {
    public string urlAsString { get; set; }
    public transient Url urlAsUrl { get { return new Url(urlAsString); } set { urlAsString = value.toExternalForm(); }}
}
DataHandler x = new DataHandler();
x.urlAsUrl = new Url('https://www.google.com');
System.debug(JSON.serialize(x));

The "transient" bit keeps JSON.serialize from handling the Url data, but it will serialize the string just fine.

Related Topic