java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
/** * This TypeAdapter unproxies Hibernate proxied objects, and serializes them * through the registered (or default) TypeAdapter of the base class. */
@SuppressWarnings({"rawtypes", "unchecked"}) @Override publicvoidwrite(JsonWriter out, HibernateProxy value)throws IOException { if (value == null) { out.nullValue(); return; } // Retrieve the original (not proxy) class Class<?> baseType = Hibernate.getClass(value); // Get the TypeAdapter of the original class, to delegate the serialization TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType)); // Get a filled instance of the original class Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer() .getImplementation(); // Serialize the value delegate.write(out, unproxiedValue); } }
使用的时候将该TypeAdapter的Factory注册到GsonBuilder,上面的代码变为
1 2 3 4 5
Gson gson = new GsonBuilder().setExcludeStrategy(ts) .registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY) .create();