开发者

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?


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.


I would consider trying out another JSON processor, Jackson (http://jackson.codehaus.org), since it has some support for dealing with cglib proxied objects. And Spring supports Jackson so you have less code to write, compared to gson-based version.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜