Gson序列化Spring bean [英] Gson serializing Spring beans

查看:171
本文介绍了Gson序列化Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Gson 1.6和 Spring Framework 3.0 for a Java web app on WebSphere 6.1 。我有一些Spring bean,其实际实例是 CGLIB 代理。当我尝试通过Gson序列化这些bean时,该类的非基元属性不会被序列化。相反,我得到如下所示:

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

在那里,我期待着更多的东西:

  {
stringProperty: stringValue
integerObjectProperty:17,
booleanProperty:true,
anotherBooleanProperty:true,
}
pre>

当我序列化一个非代理POJO时,输出与我所期望的完全一致。我怎么才能让Gson生成我期望的输出?

解决方案

我会说你的问题是一个不好的练习的结果。

Spring Bean通常是由行为定义的,而不是状态。您应该只对具有状态的类进行序列化,而不是行为。



重构代码,将状态从Beans转移到Value Objects并将其序列化。


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.

这篇关于Gson序列化Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆