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.
<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.
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);