Gson custom seralizer for one variable (of many) in an object using TypeAdapter
JavaSerializationGsonJava Problem Overview
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]
}
Java Solutions
Solution 1 - Java
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 called getDelegateAdapter()
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.
public abstract class CustomizedTypeAdapterFactory<C>
implements TypeAdapterFactory {
private final Class<C> customizedClass;
public CustomizedTypeAdapterFactory(Class<C> customizedClass) {
this.customizedClass = customizedClass;
}
@SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return type.getRawType() == customizedClass
? (TypeAdapter<T>) customizeMyClassAdapter(gson, (TypeToken<C>) type)
: null;
}
private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type) {
final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
return new TypeAdapter<C>() {
@Override public void write(JsonWriter out, C value) throws IOException {
JsonElement tree = delegate.toJsonTree(value);
beforeWrite(value, tree);
elementAdapter.write(out, tree);
}
@Override public C read(JsonReader in) throws IOException {
JsonElement tree = elementAdapter.read(in);
afterRead(tree);
return delegate.fromJsonTree(tree);
}
};
}
/**
* Override this to muck with {@code toSerialize} before it is written to
* the outgoing JSON stream.
*/
protected void beforeWrite(C source, JsonElement toSerialize) {
}
/**
* Override this to muck with {@code deserialized} before it parsed into
* the application type.
*/
protected void afterRead(JsonElement deserialized) {
}
}
The above class uses the default serialization to get a JSON tree (represented by JsonElement
), and then calls the hook method beforeWrite()
to allow the subclass to customize that tree. Similarly for deserialization with afterRead()
.
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.
private class MyClassTypeAdapterFactory extends CustomizedTypeAdapterFactory<MyClass> {
private MyClassTypeAdapterFactory() {
super(MyClass.class);
}
@Override protected void beforeWrite(MyClass source, JsonElement toSerialize) {
JsonObject custom = toSerialize.getAsJsonObject().get("custom").getAsJsonObject();
custom.add("size", new JsonPrimitive(custom.entrySet().size()));
}
@Override protected void afterRead(JsonElement deserialized) {
JsonObject custom = deserialized.getAsJsonObject().get("custom").getAsJsonObject();
custom.remove("size");
}
}
Finally put it all together by creating a customized Gson
instance that uses the new type adapter:
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new MyClassTypeAdapterFactory())
.create();
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!
Solution 2 - Java
There's another approach to this. As Jesse Wilson says, this is supposed to be easy. And guess what, it is easy!
If you implement JsonSerializer
and JsonDeserializer
for your type, you can handle the parts you want and delegate to Gson for everything else, with very little code. I'm quoting from @Perception's answer on another question below for convenience, see that answer for more details:
> In this case its better to use a JsonSerializer
as opposed to a TypeAdapter
, for the simple reason that serializers have access to their serialization context.
>
> public class PairSerializer implements JsonSerializer
However, I will acknowledge that Jesse's approach looks better if you're frequently going to modify fields in your Java object. It's a trade-off of ease-of-use vs flexibility, take your pick.
Solution 3 - Java
My colleague also mentioned the use of the @JsonAdapter
annotation
https://google.github.io/gson/apidocs/com/google/gson/annotations/JsonAdapter.html</del>
The page has been moved to here: https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/JsonAdapter.html
Example:
private static final class Gadget {
@JsonAdapter(UserJsonAdapter2.class)
final User user;
Gadget(User user) {
this.user = user;
}
}