I got an Exception when trying to convert an Exception Object to a Json Text
I got this Exception
Caused by: java.lang.StackOverflowError at java.util.ArrayList.get(ArrayList.java:322)[:1.6.0_12] at com.google.gson.stream.JsonWriter.peek(JsonWriter.java:354)
when trying to convert an Exception Object to a Json Text as the following code
Exception exception = new Exception("Test"); String gsonText = gson.toJson(exception);
You get a StackOverflowError because the exception's cause instance member variable is initialized to itself. The serializer attempts to traverse the object and never finishes because it keeps following the reference to the cause.
There's a message on the GSON google group describing this problem, the solutions suggested are:
So, you have three (exclusive) choices:
1) If you are serializing your own exceptions, modify all of your exceptions to set the cause to null, or to passed parameter upon constructing.
2) Call initCause(null) on any exceptions returning (null) from getCause() (may end up getting some IllegalStateExceptions here)
3) Write your own Serializer that would call getCause() rather than attempting to dereference "cause" field.
Also, attempting to send serialized exception code over the wire may be somewhat of a unorthodox design choice.
Usually the advice to application developers is to not show stack traces to clients, so I would suggest calling toString on the exception or otherwise mapping the exception to a message on the server-side and send the message instead.