Search code examples
jsonspringserializationgsoncglib

Gson serializing Spring beans


I am using Gson 1.6 and Spring Framework 3.0 for a Java web app on WebSphere 6.1. I have some Spring beans for which the actual instance is a CGLIB proxy. When I attempt to serialize these beans via Gson, the non-primitive properties of the class are not serialized. Instead I get something like:

{
   "CGLIB$BOUND":true,
   "CGLIB$CONSTRUCTED":true,
   "booleanProperty":true,
   "anotherBooleanProperty":true,
}

where I was expecting something more like

{
   "stringProperty":"stringValue"
   "integerObjectProperty":17,
   "booleanProperty":true,
   "anotherBooleanProperty":true,
}

When I serialize a non-proxied POJO, the output is exactly as I'd expect. How can I get Gson to generate the output I expect?


Solution

  • I'd say your problem is the result of a bad practice.

    Spring Beans are usually defined by behaviour, not state. And you should only serialize Classes that have State, not behaviour.

    Refactor your code, transfer the state from the Beans to Value Objects, and serialize those.