Use Gson to serialize a POJO

后端 未结 2 1654
不知归路
不知归路 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.

提交回复
热议问题