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

JavaSerializationGson

Java 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 { > @Override > public JsonElement serialize(final Pair value, final Type type, > final JsonSerializationContext context) { > final JsonObject jsonObj = new JsonObject(); > jsonObj.add("first", context.serialize(value.getFirst())); > jsonObj.add("second", context.serialize(value.getSecond())); > return jsonObj; > } > } > The main advantage of this (apart from avoiding complicated workarounds) is that you can still advantage of other type adaptors and custom serializers that might have been registered in the main context. Note that registration of serializers and adapters use the exact same code.

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;
   }
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMountainXView Question on Stackoverflow
Solution 1 - JavaJesse WilsonView Answer on Stackoverflow
Solution 2 - JavaVicky ChijwaniView Answer on Stackoverflow
Solution 3 - Javadazza5000View Answer on Stackoverflow