huberflores / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Add support for decorating JsonSerializer / JsonDeserializer #599

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
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 sampo.ni...@mwsoy.com on 3 Oct 2014 at 8:38