Use Gson to serialize a POJO

后端 未结 2 1655
不知归路
不知归路 2021-01-05 13:11

I use GSON serialize POJO -- both the object before and after altered.

The altered one (call it A) which is setup by Struts2 could easily serialized to Json.

<
相关标签:
2条回答
  • 2021-01-05 14:01

    It sounds like your POJO is of type Customer? When you clone your object, you're creating a new Customer, and Gson can serialize that just fine. When you fetch that same object from the DB, however, it's not a standard Customer object. Instead, it's a subclass that includes some persistence information, such as the class of the object.

    Probably the simplest solution is to use Gson's @Expose annotation. If you create your Gson object with new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(), then you can mark each of the Customer fields that you would like to serialize with @Expose. Any other fields, including those of your persistence framework's subclass, will not be serialized.

    0 讨论(0)
  • 2021-01-05 14:02

    Brandon was right. Here is another solution if you don't want to use any annotation or modify your POJO class. This may help for any other guys.

    Type typeOfSrc = new TypeToken<A>() {}.getType(); //this helps for generic one.
    gson.toJson(obj, typeOfSrc); or gson.toJson(obj, A.class);
    
    0 讨论(0)
提交回复
热议问题