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
As @madhead mentioned in the comments, this happens because, depending on the situation, Hibernate creates proxies around your object, which will call the actual implementation for some methods, and a "instrumented" one for others. Thus, the "actual" type of your objects are HibernateProxy. You can get access to your implementation by using a code similar to the one described here . In your case, you'd have to call the "unproxy" method for each item in your list, putting them into a new list.
I have resolved my problem. The assumption about HibernateProxy
objects seemed to be very probable. However everything has started to work properly when I have read carefully my error. Finally I have registered type adapter in this way:
public String messagesToJson(List<Message> messages) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.registerTypeAdapter(Message.class, new MessageAdapter()).create();
return gson.toJson(messages);
}
Any my MessageAdapter
class looks like:
public class MessageAdapter implements JsonSerializer<Message> {
@Override
public JsonElement serialize(Message message, Type type, JsonSerializationContext jsc) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("message_id", message.getMessageId());
jsonObject.addProperty("message", message.getMessage());
jsonObject.addProperty("user", message.getUsers().getUsername());
jsonObject.addProperty("date", message.getDate().toString());
return jsonObject;
}
}
And thats all. Now I can get JSONs in jQuery using AJAX properly.
Though pretty old to answer, I guess by just creating a DTO for Message with String fields would solve the purpose.