How to properly convert List of specific objects to Gson?

Viewed 17556

I am working on Spring MVC project. I am using Hibernate. I want to use AJAX with jQuery to get some JSONs from my Spring Controllers. Unfortunately when I was implementing Gson methods in my application I have got an error:

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

Which adapter I have to use and in which way? The error has occurred on the last line of the method:

public String messagesToJson(List<Message> messages) {
    Gson gson = new Gson();     
    List<Message> synchronizedMessages = Collections.synchronizedList(messages);
    return gson.toJson(synchronizedMessages, ArrayList.class);
}

This is my Message class I am using in my Spring MVC project with Hibernate:

@Entity
@Table(name = "MESSAGES", schema = "PUBLIC", catalog = "PUBLIC")
public class Message implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private int messageId;
    private User users;
    private String message;
    private Date date;

    //Constructor, getters, setters, toString
}

EDIT

I am wondering: my Message object is proxied or the whole List<Message>? I am getting the list of messages in this way:

public List<Message> findAllUserMessages(String username) {
    Query query = entityManager.createQuery("from Message where username = :username order by date desc")
            .setParameter("username", username);

    @SuppressWarnings("unchecked")
    List<Message> messages = query.getResultList();
    return messages;
}

EDIT 2

No, my List<Message> object isn't proxied.

3 Answers

Though pretty old to answer, I guess by just creating a DTO for Message with String fields would solve the purpose.

Related