4

I have a simple return class that either takes an exception or one of our business objects. If the REST web service method throws an exception, it catches it and sets the exception in the response. If not, it sets the return value in the response and serializes it.

In my case, I'm getting an InvocationTargetError that wraps one of our service exceptions. I set this on my exception on my return class and get the following stack trace:

java.lang.StackOverflowError
com.google.gson.reflect.TypeToken.hashCode(TypeToken.java:280)
java.util.HashMap.get(HashMap.java:300)
java.util.Collections$SynchronizedMap.get(Collections.java:1975)
com.google.gson.Gson.getAdapter(Gson.java:337)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:55)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
and so on...

Anyone have any ideas? This looks like a bug in Gson 2.2.2.

David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
Thom
  • 14,013
  • 25
  • 105
  • 185
  • 2
    Did you make sure there are no circular references? http://stackoverflow.com/questions/10209959/gson-tojson-throws-stackoverflowerror (That' what had happend to me) – MartinK Nov 20 '12 at 15:50
  • 1
    It's an exception. What would be circular? – Thom Nov 20 '12 at 16:35
  • 1
    Scratching my head - Turns out Throwable's `cause` field is the problem. See http://groups.google.com/forum/?fromgroups=#!topic/google-gson/hFpBXbudMRQ – MartinK Nov 20 '12 at 17:15

2 Answers2

6

Gson can't handle circular references in the serialized data. Chances are you have one. Fix that and you've fixed your problem.

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • Turns out all exceptions have circular references. Who'd've thunk it. Can't figure that one out. – Thom Nov 21 '12 at 10:01
  • 1
    So how does one... "fix that"? It's kind of by design that a user object contains an arraylist of users (people you follow). – Luc Apr 25 '16 at 07:33
3

I created an issue for this on the google code site.

http://code.google.com/p/google-gson/issues/detail?id=488

Thom
  • 14,013
  • 25
  • 105
  • 185