Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson custom seralizer for one variable (of many) in an object using TypeAdapter

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] } 
like image 788
MountainX Avatar asked Jun 30 '12 04:06

MountainX


1 Answers

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!

like image 168
Jesse Wilson Avatar answered Oct 02 '22 14:10

Jesse Wilson