java – 使用Gson序列化POJO

前端之家收集整理的这篇文章主要介绍了java – 使用Gson序列化POJO前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用GSON序列化POJO – 改变之前和之后的对象.

由Struts2设置的改变的(称为A)可以很容易地序列化为Json.

虽然通过iBatis(称为B)从数据库获取的更改前的POJO无法序列化.

错误消息说:忘记注册类型适配器?

我已经阅读了Gson API.但我不认为为每个POJO注册一个类型适配器是一个好主意.什么使B无法序列化?

我为我的POJO编写了一个clone(),也可以完成从B克隆的对象.

这令人困惑……有人能回答我吗?

在改变之前(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"}

改变后(A):

{"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":"意向"}

解决方法

听起来你的POJO属于Customer类型?当你克隆你的对象时,你正在创建一个新的Customer,而Gson可以很好地序列化它.但是,从DB获取同一对象时,它不是标准的Customer对象.相反,它是一个包含一些持久性信息的子类,例如对象的类.

可能最简单的解决方案是使用Gson的@Expose注释.如果使用新的GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()创建Gson对象,则可以使用@Expose标记要序列化的每个Customer字段.任何其他字段,包括持久性框架的子类的字段,都不会被序列化.

猜你在找的Java相关文章