1

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.

5
  • Can you add sample JSON? Commented Apr 18, 2018 at 22:07
  • @PranayJaiswal I'm trying to serialize a Url object to JSON, so I don't have any sample JSON to give. Commented Apr 18, 2018 at 22:09
  • 1
    @KevinVizcarra hes talking about the object you're trying to serialize
    – EricSSH
    Commented Apr 18, 2018 at 22:11
  • 1
    You're going to have to change the properties to String. Why do you want to leave them as URL? You seem to be having a bit of an X-Y Problem here.
    – Adrian Larson
    Commented Apr 18, 2018 at 22:15
  • I tried debugging the URL's toString method. It looks like that object was not designed to be serialised. If you force it to serialize it will form a malformed JSON. .-----> System.debug(JSON.serialize(new Url('google.com').toString())); Commented Apr 18, 2018 at 22:17

1 Answer 1

4

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .