我使用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, 2012 12:00:00 AM","purpose":"未选择","education":"未选择","income":"未选择","cars":"未选择","acptCarpRent":"未选择","acptCarpPrice":"未选择","handStand":"未选择","intentHouse":"未选择","intentArea":"未选择","intentLayout":"未选择","nextDate":"Mar 7, 2012 12:00:00 AM","wuyeType":"未选择","attentionPro":"958B9E093A84415B901900C2DA25C712","ordinaryTraffic":"未选择","attentionPoint":"未选择","buyDate":"未选择","cityArea":"未选择","lastUpdate":"Feb 29, 2012 12:00:00 AM","lastModifier":"EE4783A6272A4B62A5CC68DB3C11FE1E","saler":"A4FB4877DC2945E980477544A955B57F","state":"意向","status":"0"}
改变后(A):
{"id":"6429B5329C544711A9848AF243D10E4E","idType":"未选择","firstDate":"Feb 29, 2012 12:00:00 AM","visitMode":"","name":"testetes","gender":"男","telPhone":"","phone":"553223","fax":"","adrs":"","postCode":"","email":"","workUnit":"","city":"未选择","media_id":"","ocup":"未选择","idNum":"","nation":"未选择","famStru":"未选择","infSouc":"未选择","createDate":"Feb 29, 2012 12:00:00 AM","idAdr":"","purpose":"未选择","education":"未选择","income":"未选择","cars":"未选择","acptCarpRent":"未选择","acptCarpPrice":"未选择","handStand":"未选择","intentHouse":"未选择","intentArea":"未选择","intentLayout":"未选择","customerDetail":"","wuyeType":"未选择","attentionPro":"958B9E093A84415B901900C2DA25C712","ordinaryTraffic":"未选择","attentionPoint":"未选择","buyDate":"未选择","cityArea":"未选择","lastUpdate":"Mar 11, 2012 2:58:04 PM","lastModifier":"00000000000000000000000000000000","saler":"A4FB4877DC2945E980477544A955B57F","state":"意向"}
答案 0 :(得分:10)
听起来您的POJO属于Customer类型?当你克隆你的对象时,你正在创建一个新的Customer,而Gson可以很好地序列化它。但是,从DB获取同一对象时,它不是标准的Customer对象。相反,它是一个包含一些持久性信息的子类,例如对象的类。
可能最简单的解决方案是使用Gson的@Expose
注释。如果使用new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
创建Gson对象,则可以使用@Expose
标记要序列化的每个Customer字段。
答案 1 :(得分:2)
Type typeOfSrc = new TypeToken<A>() {}.getType(); //this helps for generic one.
gson.toJson(obj, typeOfSrc); or gson.toJson(obj, A.class);