google / google/gson

Add support for decorating JsonSerializer / JsonDeserializer

Open
#599 4 comments 5 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

```
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.