Gson: Add support for decorating JsonSerializer / JsonDeserializer

Created on 19 Mar 2015  路  4Comments  路  Source: google/gson

Currently, if you call context.serialize from a JsonSerializer with the 
argument object, you get an infinite loop (as is explained in the Javadoc).  
This is problematic, because there is no way to use the decorator pattern for a 
JsonSerializer.

Example use cases:
- serialize normally and add some extra properties to the output (e.g. class 
type information)
- either perform normal serialization or special handling depending on some 
fields (instead of according to the registered class type)

My specific use case was trying to add class information to the serialized 
output, as described here:  
https://groups.google.com/forum/#!topic/google-gson/qFAosu6SdY4

JsonSerializationContext.serialize should essentially be "serialize using this 
GSON instance, but do not call myself again with the current object".  Since 
the serialize methods currently always cause a StackOverflowException in this 
case, this would be a backward-compatible change.  The same should be done for 
JsonDeserializationContext.deserialize.

This would ease a lot of serialization use cases.  For example, it would make 
it very easy to write a serializer/deserializer that adds class type 
information to the JSON output and deserializes according to it, without the 
need to registering the types beforehand (as RuntimeTypeAdapterFactory 
requires).

Original issue reported on code.google.com by [email protected] on 3 Oct 2014 at 8:38

Most helpful comment

This is spot on our use case to. Is there any fix / workaround / reason not to.
To me this is the expected behavior

All 4 comments

This is spot on our use case to. Is there any fix / workaround / reason not to.
To me this is the expected behavior

@mathiasbn consider TypeAdapterFactory, which supports this kind of thing.

Although this solution is a little dirty, you could alternatively declare a new Gson instance in your JsonSerializer and call gson.toJsonTree. You'd then be able to decorate the jsonElement without running into the infinite loop.

Wauw after 1.5 years.
@IgorBelyayev yes thank you. We did use that a bit, but it just felt to weird. Plus if you have 10 serializers/deserializers you need 11 gson instances. One with all, and 10 with all but one. And then it still doesn`t work for nested types.
We ended up using the RuntimeTypeAdapterFactory which we ported from an unreleadsed (at least back then) version.

I still think the pattern described should be possible thou

Was this page helpful?
0 / 5 - 0 ratings

Related issues

GoogleCodeExporter picture GoogleCodeExporter  路  31Comments

GoogleCodeExporter picture GoogleCodeExporter  路  14Comments

GoogleCodeExporter picture GoogleCodeExporter  路  25Comments

LucianWang picture LucianWang  路  42Comments

GoogleCodeExporter picture GoogleCodeExporter  路  20Comments