6

I'm using a Restful web service (Jersy implementation) with a JSF application and used Json to get the data as follows:

    carObjectDao = new GenericDAO<carObject>(carObject.class);
    List<carObject> allCars = carObjectDao.readAll();
    Gson gson = new Gson();
    String carString = gson.toJson(allCars);
    System.err.println(carString );
    return carString ;

i run the application in debug mode and allCars is filled with the data correctly, but after that an exception is thrown :

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

i don't know the root cause of the exception

Eslam Hamdy
  • 7,126
  • 27
  • 105
  • 165

2 Answers2

6

This is a known problem: Could not serialize object cause of HibernateProxy

JSon can't deserialize HibernateProxy objects, so you either unproxy or remove em.

Or, you can eager fetch the lazy data.

Community
  • 1
  • 1
Ziul
  • 883
  • 1
  • 13
  • 24
  • 1
    How to Unproxy or remove them, i read that post but didn't understand – Eslam Hamdy May 15 '13 at 23:01
  • Fist you have to undestand how the lazy initialization works, when you dont eager fetch a collection, or load an object, it comes as a Hibernate proxy collection/object, you have to find out from your allCars objects, which child collection/objects are coming as HibernateProxy instead of real data. – Ziul May 15 '13 at 23:28
  • After that, you can decide what to do with em (remove em or fix em). – Ziul May 15 '13 at 23:30
0

Try parsing through ObjectMapper as

    carObjectDao = new GenericDAO<carObject>(carObject.class);
    List<carObject> allCars = carObjectDao.readAll();
    String carString = new ObjectMapper().writeValueAsString(allCars);
    System.err.println(carString );
    return carString ;