Java – serialize POJOs using gson

I use gson to serialize POJOs – objects before and after changes

The changed (called a) set by struts 2 can be easily serialized as JSON

Although the pre - change POJOs obtained from the database through ibatis (called B) cannot be serialized

The error message says: forgot to register the type adapter?

I have read the gson API But I don't think it's a good idea to register a type adapter for each POJO What makes b unable to serialize?

I wrote a clone () for my POJO, which can also clone objects from B

It's confusing... Can anyone answer me?

Before change (clone of B):

{"id":"6429B5329C544711A9848AF243D10E4E","idType":"未选择","firstDate":"Feb 29,2012 12:00:00 AM","name":"testetes","gender":"男","phone":"553223","city":"未选择","ocup":"未选择","nation":"未选择","famStru":"未选择","infSouc":"未选择","creater":"EE4783A6272A4B62A5CC68DB3C11FE1E","createDate":"Feb 29,"purpose":"未选择","education":"未选择","income":"未选择","cars":"未选择","acptCarpRent":"未选择","acptCarpPrice":"未选择","handStand":"未选择","intentHouse":"未选择","intentArea":"未选择","intentLayout":"未选择","nextDate":"Mar 7,"wuyeType":"未选择","attentionPro":"958B9E093A84415B901900C2DA25C712","ordinaryTraffic":"未选择","attentionPoint":"未选择","buyDate":"未选择","cityArea":"未选择","lastUpdate":"Feb 29,"lastModifier":"EE4783A6272A4B62A5CC68DB3C11FE1E","saler":"A4FB4877DC2945E980477544A955B57F","state":"意向","status":"0"}

After change:

{"id":"6429B5329C544711A9848AF243D10E4E","visitMode":"","telPhone":"","fax":"","adrs":"","postCode":"","email":"","workUnit":"","media_id":"","idNum":"","idAdr":"","customerDetail":"","lastUpdate":"Mar 11,2012 2:58:04 PM","lastModifier":"00000000000000000000000000000000","state":"意向"}

Solution

Sounds like your POJO is of customer type? When you clone your object, you are creating a new customer, and gson can serialize it well However, when getting the same object from DB, it is not a standard customer object Instead, it is a subclass that contains some persistence information, such as the class of an object

Perhaps the simplest solution is to use gson's @ expose annotation If you use the new gsonbuilder() excludeFieldsWithoutExposeAnnotation(). Create() creates a gson object, you can use @ expose to mark each customer field to be serialized Any other fields, including those of subclasses of the persistence framework, are not serialized

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>