98

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]
}
MountainX
  • 6,217
  • 8
  • 52
  • 83

3 Answers3

135

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!

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • I wasn't able to instantiate `new MyClassTypeAdapterFactory()` with the private ctor... – MountainX Jun 30 '12 at 17:13
  • Ah, sorry about that. I did all of this in one file. – Jesse Wilson Jul 01 '12 at 02:05
  • In the MyClassTypeAdapterFactory.afterRead() method, I need to serialize something and add it to the "deserialized" JsonElement. How can I get a JsonSerializationContext object from that method? – pacoverflow Feb 09 '13 at 04:16
  • 7
    That mechansim (beforeWrite and afterRead) should be part of GSon core. Thanks! – Melanie Feb 21 '13 at 16:57
  • 2
    I am using TypeAdapter to avoid infinite loops due to mutual referencing.. this is a great mechanism thank you @Jesse although I'd like to ask if you have an idea of achieving same effect with this mechanism.. I have things in mind but I want to listen to your opinion.. thank you! – Mohammed R. El-Khoudary Sep 27 '14 at 19:36
  • Awesome! Thanks for the snippet! Question, how would you use this pattern if C's super class had it's own TypeAdapter (you would want beforeWrite and afterRead from the super to be called), I can't figure a way to achieve this so far. – Fabien Demangeat May 19 '15 at 14:14
  • Thats an excellent approach. I am using it to unflatten JSON which is formatted according to the JSON-API specification http://jsonapi.org/. Its about the same approach than my initial solution, but way more elegant. Here is the Gist of my implementation:https://gist.github.com/wischweh/c55265d0883c4e4ab350 – r-hold Jul 03 '15 at 13:45
  • Do you need two factories, one for each adapter, if you have two custom adapters who both need to use their own delegate adapter but each others custom adapters? And @MohammedR.El-Khoudary how do you avoid infinite loops with TypeAdapter exactly? – Espen Riskedal Sep 19 '16 at 20:23
  • @Espen Riskedal I'm also curious about the situation when more than one customized adapters are needed. Have you got any clue? – LittleLittleQ Apr 10 '17 at 04:00
  • @AnnabellChan I just added several classes to the same factory. I believe several factories are supported if you need it. – Espen Riskedal Apr 10 '17 at 08:50
  • awesome : you save my life . I've just made a little bit of changes : beforeRead and AfterRead return a JsonElement (not void) to be able to change not only the content of the provided JsonElement but also the element itself as well. (my use case was : change a particular JsonObject into a JsonArray. : nashorn js array in handled as an Map with key as integer index internally: js {"a":["A","B"]} is stringify by Gson as {"a":{"0":"A","1":"B"}}.. nashorn JSON.stringify failed if the object does make reference to some Java object (mixed js and Java object)) – Emmanuel Devaux Jul 27 '18 at 14:53
  • API doc links are dead. –  Aug 01 '18 at 15:02
  • This just made my day. Now I can easily setup a few adapters for the edge cases where I need to keep null values in my json output ! – slott Sep 07 '18 at 11:55
16

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<Pair> {
    @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.

Community
  • 1
  • 1
Vicky Chijwani
  • 10,191
  • 6
  • 56
  • 79
11

My colleague also mentioned the use of the @JsonAdapter annotation

https://google.github.io/gson/apidocs/com/google/gson/annotations/JsonAdapter.html

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;
   }
 }
Zhwt
  • 426
  • 3
  • 13
dazza5000
  • 7,075
  • 9
  • 44
  • 89
  • 1
    This works pretty well for my use case. Thanks a lot. – Neoklosch Dec 11 '18 at 14:23
  • 1
    Here's a WebArchive link because the original is now dead: https://web.archive.org/web/20180119143212/https://google.github.io/gson/apidocs/com/google/gson/annotations/JsonAdapter.html – Floating Sunfish Jun 20 '19 at 06:20