How to properly convert List of specific objects to Gson?

后端 未结 3 901
野的像风
野的像风 2020-12-30 02:36

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

相关标签:
3条回答
  • 2020-12-30 03:17

    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.

    0 讨论(0)
  • 2020-12-30 03:23

    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.

    0 讨论(0)
  • 2020-12-30 03:27

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

    0 讨论(0)
提交回复
热议问题