Gson serializing Spring beans

喜你入骨 提交于 2019-12-12 20:41:25

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5980379/gson-serializing-spring-beans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!