Adding class information to serialized objects

222 views
Skip to first unread message

Sampo Niskanen

unread,
Sep 26, 2014, 9:14:59 AM9/26/14
to googl...@googlegroups.com
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.




Martin Grajcar

unread,
Sep 26, 2014, 1:18:59 PM9/26/14
to googl...@googlegroups.com
> 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.)

+1 Something similar could be used also for cases when you need to handle only one direction, e.g., for an ImmutableListAdapter which could delegate serialization to the context without itself.

Sampo Niskanen

unread,
Oct 3, 2014, 4:41:01 AM10/3/14
to googl...@googlegroups.com
FYI, I submitted a feature request for allowing decorating JsonSerializer / JsonDeserializer:  http://code.google.com/p/google-gson/issues/detail?id=599

Regards,
   Sampo N.
 
Reply all
Reply to author
Forward
0 new messages