Gson automatically add classname

gson, java

Solution

Take a look at this: http://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java

RuntimeTypeAdapterFactory<BillingInstrument> rta = RuntimeTypeAdapterFactory.of(
    BillingInstrument.class)
    .registerSubtype(CreditCard.class);
Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(rta)
    .create();

CreditCard original = new CreditCard("Jesse", 234);
assertEquals("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}",
    gson.toJson(original, BillingInstrument.class));

Problem

Lets say I have the following classes: ``` public class Dog { public String name = "Edvard"; } public class Animal { public Dog madDog = new Dog(); } ``` If I run this trough a Gson it will serialize it as following: ``` GSon gson = new GSon(); String json = gson.toJson(new Animal()) result: { "madDog" : { "name":"Edvard" } } ``` This far so good, but I would like to have added the className for all classes automatically with Gson, so I get the following result: ``` { "madDog" : { "name":"Edvard", "className":"Dog" }, "className" : "Animal" } ``` Does anyone know if this is possible with some kind of interceptors or something with Gson?

Original source