GSON 报错HibernateProxy. Forgot to register a type adapter? 的解决办法

来源:互联网 发布:淘宝一件代发挣钱吗 编辑:程序博客网 时间:2024/06/06 02:53
使用Gson转换hibernate对象遇到一个问题,当对象的Lazy加载的,就会出现上面的错误。处理方式摘抄自网上,留存一份以后自己看。

 

网上找到的解决办法,首先自定义一个类继承TypeAdapter:

 1 package cn.xjy.finance.loanapply.utils ; 2  3 import java.io.IOException ; 4 import org.hibernate.Hibernate ; 5 import org.hibernate.proxy.HibernateProxy ; 6 import com.google.gson.Gson ; 7 import com.google.gson.TypeAdapter ; 8 import com.google.gson.TypeAdapterFactory ; 9 import com.google.gson.reflect.TypeToken ;10 import com.google.gson.stream.JsonReader ;11 import com.google.gson.stream.JsonWriter ;12 13 /** 14  * This TypeAdapter unproxies Hibernate proxied objects, and serializes them 15  * through the registered (or default) TypeAdapter of the base class. 16  */17 public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {18     19     public static final TypeAdapterFactory    FACTORY    = new TypeAdapterFactory() {20         @Override21         @SuppressWarnings("unchecked")22         public <T> TypeAdapter<T> create(Gson gson,23                 TypeToken<T> type) {24             return (HibernateProxy.class25                     .isAssignableFrom(type26                             .getRawType()) ? (TypeAdapter<T>) new HibernateProxyTypeAdapter(27                     gson) : null) ;28         }29     } ;30                                                     31     private final Gson                        context ;32     33     private HibernateProxyTypeAdapter(Gson context) {34         this.context = context ;35     }36     37     @Override38     public HibernateProxy read(JsonReader in) throws IOException {39         throw new UnsupportedOperationException("Not supported") ;40     }41     42     @SuppressWarnings({ "rawtypes", "unchecked" })43     @Override44     public void write(JsonWriter out, HibernateProxy value) throws IOException {45         if (value == null) {46             out.nullValue() ;47             return ;48         }49         // Retrieve the original (not proxy) class50         Class<?> baseType = Hibernate.getClass(value) ;51         // Get the TypeAdapter of the original class, to delegate the52         // serialization53         TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType)) ;54         // Get a filled instance of the original class55         Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()56                 .getImplementation() ;57         // Serialize the value58         delegate.write(out, unproxiedValue) ;59     }60 }

 

然后初始化gson对象的方式:

1 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd")2                                                     .registerTypeAdapterFactory(3                                                     HibernateProxyTypeAdapter.FACTORY).create() ;                

这样就解决了,出现这个错误的主要原因是,hibernate采取懒加载的方式查询数据库,也就是只有用到了才去查真正的数据,用不到的话只是返回一个代理对象,gson识别不了代理对象,所以没法转换.

阅读全文
0 0
原创粉丝点击