摘要: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?

使用Gson转换Hibernate对象遇到一个问题,当对象的Lazy加载的,就会出现上面的错误。处理方式摘抄自网上,留存一份以后自己看。

  1. /**

  2. * This TypeAdapter unproxies Hibernate proxied objects, and serializes them

  3. * through the registered (or default) TypeAdapter of the base class.

  4. */

  5. public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {

  6. public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {

  7. @Override

  8. @SuppressWarnings("unchecked")

  9. public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

  10. return (HibernateProxy.class.isAssignableFrom(type.getRawType()) ? (TypeAdapter<T>) new HibernateProxyTypeAdapter(gson) : null);

  11. }

  12. };

  13. private final Gson context;

  14. private HibernateProxyTypeAdapter(Gson context) {

  15. this.context = context;

  16. }

  17. @Override

  18. public HibernateProxy read(JsonReader in) throws IOException {

  19. throw new UnsupportedOperationException("Not supported");

  20. }

  21. @SuppressWarnings({"rawtypes", "unchecked"})

  22. @Override

  23. public void write(JsonWriter out, HibernateProxy value) throws IOException {

  24. if (value == null) {

  25. out.nullValue();

  26. return;

  27. }

  28. // Retrieve the original (not proxy) class

  29. Class<?> baseType = Hibernate.getClass(value);

  30. // Get the TypeAdapter of the original class, to delegate the serialization

  31. TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));

  32. // Get a filled instance of the original class

  33. Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()

  34. .getImplementation();

  35. // Serialize the value

  36. delegate.write(out, unproxiedValue);

  37. }

  38. }

实现上面的类,然后就是使用:

  1. GsonBuilder b = new GsonBuilder();

  2. ...

  3. b.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);

  4. ...

  5. Gson gson = b.create();

解释,只是看不懂。

GSON contains a number of TypeAdapterFactory implementations, for various types (primitive types, common types like String or Date, lists, arrays...). Each factory is asked if it is able to serialize a certain Java type (the parameter to create is a TypeToken instead of a Class in order to capture possible information about generic types, which Class does not have). If the factory is able to serialize/deserialize a type, it responds with a TypeAdapter instance; otherwise it responds with null.

HibernateProxyTypeAdapter.FACTORY verifies whether type implements HibernateProxy; in that case, it returns an instance of HibernateProxyTypeAdapter for serialization. The write method is called when an actual object has to be serialized; the adapter extracts the original type of the underlying object, and asks GSON for the standard TypeAdapter for the original type, which generally is a ReflectiveTypeAdapter.

Then it retrieves an instance of the original class, instead of directly using the proxy. This is necessary because ReflectiveTypeAdapter accesses directly to fields, instead of using getters; accessing to the fields of a proxied object does not work, and is a classical Hibernate pitfall.

As a possible performance improvement, the delegate TypeAdapter should be acquired in the create method. I found out that calling getSuperclass() on the proxy Class appears to yield the original base class.

--------------------- 本文来自 xspwz123 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xspwz123/article/details/71425545?utm_source=copy

重点技术-20181008-GSON 报错HibernateProxy. Forgot to register a type adapter?相关推荐

  1. springboot出现“org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?“的解决办法

    springboot出现"Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot ...

  2. 异常org.hibernate.proxy.HibernateProxy.Forgot to register a type adapter

    今天遇到一个这样的问题,发现是是对象代理的原因,将转换json对象中的代理对象赋为空即可: <pre name="code" class="java"&g ...

  3. Attempted to serialize java.lang.Class: com.cao.bean.DmCategory. Forgot to register a type adapter?

    使用mybatis从数据库获取的数据,用gson进行传参出现错误以下报错: 我使用的mybatis是采取懒加载的方式查询数据库,也就是只有用到了才去查真正的数据,用不到的话只是返回一个代理对象,gso ...

  4. VMBox加载拷贝的vid报错E_INVALIDARG (0x80070057) Cannot register the hard disk 'D:\VMBox\win7.vdi' {7bca5a3

    VMBox加载拷贝的vid报错E_INVALIDARG (0x80070057) Cannot register the hard disk 'D:\VMBox\win7.vdi' {7bca5a3e ...

  5. 关于配置双数据源报错org.apache.ibatis.binding.BindingException: Type interface is not known to the MapperRegis

    报错org.apache.ibatis.binding.BindingException: Type interface is not known to the MapperRegistry.,在网上 ...

  6. auto cad安装报错command line option syntax error.type command

    网上下载的cad2012安装包,自己解压出来按照发现报错command line option syntax error.type command,大概意思就是安装包不能包含中文目录,最后的解决办法就 ...

  7. SpringCloud - 整合Nacos启动报错Consider defining a bean of type IClientConfig

    SpringCloud - 整合Nacos启动报错Consider defining a bean of type IClientConfig 前言 一. 尝试解决Bug的几种不合适方案 1.1 添加 ...

  8. 解决启动报错Consider defining a bean of type ‘xxx‘ in your configuration.

    解决启动报错Consider defining a bean of type 'xxx' in your configuration. 报错截图 解决方法:查看注解是否同时存在@AllArgsCons ...

  9. 报错: Cannot convert value of type ‘java.lang.String‘ to required type

    报错: Cannot convert value of type 'java.lang.String' to required type Caused by: java.lang.IllegalSta ...

最新文章

  1. BigInteger类实例的构造过程——JDK源码解析
  2. python实现高校教务管理系统_python实现教务管理系统
  3. 关于第三周——回顾与修正
  4. hapi和typescript构建项目(正在更新中)
  5. 书店售书最低价格问题
  6. 需求与业务的区别、需求设计与业务设计的区别
  7. 在日本做开发的日子(工作篇 序)
  8. 认识进程 java 1615387415
  9. python执行过程_Python threading模块condition原理及运行流程详解
  10. [leetcode-117]填充每个节点的下一个右侧节点指针 II
  11. Eclipse 快捷键整理
  12. java mongo分组统计_mongodb 分组 topN
  13. One Pixel Attack for Fooling Deep Neural Networks论文解读
  14. win7安装sqlserver2014
  15. android中java中的开方
  16. 合取范式 (CNF)
  17. 有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。请设计一个算法,计算机器人有多少种走法。 给定两个正整数int x,int y,请返回机器人的走法数目。保证x+y小
  18. 自步学习(Self-paced Learning)
  19. 电梯卫士等对计算机的应用,小班安全活动教案:电梯小卫士教案
  20. WAIC | 九章云极方磊:Hypernets——自动化机器学习的基础框架

热门文章

  1. jQuery插件autoComplete介绍(10级学员 张帅鹏总结)
  2. [OpenGL] shadow mapping(实时阴影映射)
  3. 新手怎样学好SEO搜索引擎优化
  4. vue-router使用history模式配置说明
  5. 干货分享:Totoro 在自动化测试领域的深耕与收获
  6. 领域驱动设计系列文章(1)——通过现实例子显示领域驱动设计的威力
  7. 【Java 8 新特性】Java 8 Collectors示例
  8. discuz 获取所有版块并按父子层级排版
  9. 博南石上海公司的那个hr,貌似叫什么harvey hou,太恶心了。。。
  10. Linux下Open函数