Hi,
I'm trying to add class type information to the serialized output of Gson, so that it could deserialize into the correct types when using generics. Essentially, what I want is RuntimeTypeAdapterFactory [1], but which works for any object, stores the full class name, and thus doesn't need registering of subtypes. (The type info would be added to any type that does not directly map into some specific json type.)
My first idea was the following:
Add a JsonSerializer for Object.class that:
- serializes the object
- if the serialized element is a JsonObject and the original object is not a Collection, add "$class" field to the JsonObject
- return the (possibly modified) JsonElement
The corresponding JsonDeserializer would check each JsonObject for the "$class" field, and deserialize to that type if present.
The problem is that it seems impossible to decorate a JsonSerializer. If I call context.serialize with the provided element, I get an infinite loop. If I use a plain Gson object for the purpose, the custom serializer won't apply on subelements. (The JsonSerializationContext should contain a method "serialize, but do not call me again for the current object" for the decoration pattern to be possible. This could be incorporated in an API-compatible way, as currently the call inevitably results in a StackOverflowException.)
Is adding full class information to all (non-primitive, non-Map) objects possible with Gson?
Best regards,
Sampo N.