I've seen plenty of simple examples of using a custom TypeAdapter. The most helpful has been Class TypeAdapter<T>
. But that hasn't answered my question yet.
I want to customize the serialization of a single field in the object and let the default Gson mechanism take care of the rest.
For discussion purposes, we can use this class definition as the class of the object I wish to serialize. I want to let Gson serialize the first two class members as well as all exposed members of the base class, and I want to do custom serialization for the 3rd and final class member shown below.
public class MyClass extends SomeClass {
@Expose private HashMap<String, MyObject1> lists;
@Expose private HashMap<String, MyObject2> sources;
private LinkedHashMap<String, SomeClass> customSerializeThis;
[snip]
}
Best Answer
This is a great question because it isolates something that should be easy but actually requires a lot of code.
To start off, write an abstract
TypeAdapterFactory
that gives you hooks to modify the outgoing data. This example uses a new API in Gson 2.2 calledgetDelegateAdapter()
that allows you to look up the adapter that Gson would use by default. The delegate adapters are extremely handy if you just want to tweak the standard behavior. And unlike full custom type adapters, they'll stay up-to-date automatically as you add and remove fields.The above class uses the default serialization to get a JSON tree (represented by
JsonElement
), and then calls the hook methodbeforeWrite()
to allow the subclass to customize that tree. Similarly for deserialization withafterRead()
.Next we subclass this for the specific
MyClass
example. To illustrate I'll add a synthetic property called 'size' to the map when it's serialized. And for symmetry I'll remove it when it's deserialized. In practice this could be any customization.Finally put it all together by creating a customized
Gson
instance that uses the new type adapter:Gson's new TypeAdapter and TypeAdapterFactory types are extremely powerful, but they're also abstract and take practice to use effectively. Hopefully you find this example useful!