RCM SAS
RCM SAS

Reputation: 95

How to deal with GSON with nested abstract classes?

i read a lot about the use of TypeAdapter and JsonSerializer/Deserializer to deal with abstract class, my problem is in case of nested abstract class. Let say this class:

abstract class A {
  String content;
}

abstract class G {
  String otherContent;
}

class B extends A {
  G g;
}

class C extends A {
  String someThing;
}

class H extends G {
  Integer num;
}

I already coded a JsonSerializer/Deserializer class for each abstract class A and G. I know I can use the chaining on: gsonbuilder.registerTypeAdapter(A_Adapter).registerTypeAdapter(G_Adapter), but i need to use something more like the TypeAdapterFactory to identify witch adapter to use (to specify the adapter class corresponding to the abstract class i used a java annotaion/reflection). I also seen the TypeAdapter class but it too complex to implement due to the missing of the context element present in the JsonSerializer/Deserializer.

Any idea how to do it?

Upvotes: 2

Views: 778

Answers (1)

varren
varren

Reputation: 14731

To use same serializer and desrializer for every subtype of Aclass(A+B+C) you can use registerTypeHierarchyAdapter(A.class, new A_Adapter()) From documentation:

Configures Gson for custom serialization or deserialization for an inheritance type hierarchy. This method combines the registration of a TypeAdapter, JsonSerializer and a JsonDeserializer. If a type adapter was previously registered for the specified type hierarchy, it is overridden. If a type adapter is registered for a specific type in the type hierarchy, it will be invoked instead of the one registered for the type hierarchy.

Upvotes: 1

Related Questions