AFAIK the most flexible gson customization is possible via TypeAdapterFactory, however it may get needlessly complicated. It forces me to write for each handled class both read and write, while sometimes only one method is really needed. Moreover, sometimes a JsonSerializer and/or JsonDeserializer were much easier to write, e.g. like here. This leads me to these questions:
- Is it possible to write a
TypeAdapterwhich simply delegates one of its methods (e.g. writing ofImmutableListto writing ofList)? - Is it possible to somehow use
JsonSerializerand/orJsonDeserializertogether with theTypeAdapterFactory? Alternatively, is there a factory for them?
It is possible to create a
TypeAdapterthat delegates one of its methods. This use case is an important part of the API, and there’s a getDelegateAdapter() method for just this purpose. Passthisas the first argument togetDelegateAdapterwhich will return the adapter that takes precedence after the current factory.You can mix and match
JsonSerializer/JsonDeserializerwithTypeAdapterFactory, but not directly. The simplest way is to call back into Gson to serialize child values in your class. In this example we’d change the inner loop to this:The main difference between
JsonSerializer/JsonDeserializerandTypeAdapteris how many stages it takes to go from JSON to your object model. WithJsonSerializer/JsonDeserializerobjects are first converted to Gson’s DOM model (JsonElementetc.) and then converted into your object model. WithTypeAdapter, the intermediate step is skipped.This makes the type adapter code a little trickier to read and write, so you should prefer it only for optimized code.