3

Sometimes as quick and drity debugging/introspection I leverage System.assert(false, JSON.serializePretty(<target>)) but it does not always work depending on target, ex:

System.VisualforceException: java.util.EmptyStackException ..... caused by: (cms)

Anyway to serialization regardless of any exceptions? Perhaps by writing your own serializer?

1
  • 2
    For debugging purposes? That seems absurdly over the top.
    – Adrian Larson
    Commented Jan 28, 2015 at 5:29

1 Answer 1

8

Without something like java.lang.Reflection, being able to serialize everything and anything is a pipe dream. There are three groupings of objects available in salesforce.com: things you can serialize, things you can't serialize but have a "legal" representation of how you could interpret them with your own code, and things you can't serialize and contain only data that would be useless outside the current context.

The first category are the normal things you'd expect: lists, maps, and objects (classes) that don't contain a forbidden item, and basic primitives. The second category contains some obvious and some not-so-obvious entries: Messaging.Email, Enum, JSONParser, and so on. The final category are things like System.SavePoint, which obviously has no meaning outside of the current execution context.

For the first category, just use JSON.serialize, and for the second category, choose only the types you really care about, and make some sort of lengthy if-else block somewhere, and ignore everything else, and for the last category, ignore them completely. Something like this:

try {
    System.debug(JSON.serialize(<target>);
catch(Exception e) {
    if(<target> instanceof Enum) {
        System.debug(<target>.name());
    } else if(<target> instanceof Exception) {
        System.debug(<target>.getMessage());
    } // etc...
}
2
  • This is a great answer. Upvoting the question just because this answer around how JSON serialization works and advice. Commented Jan 28, 2015 at 19:03
  • You sir are a gentleman and a scholar - thank you! Commented Jan 28, 2015 at 19:28

You must log in to answer this question.

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