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?
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));
You will need custom serializers for this. Here's an example for the Animal class above:
public class AnimalSerializer implements JsonSerializer<Animal> {
public JsonElement serialize(Animal animal, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jo = new JsonObject();
jo.addProperty("className", animal.getClass().getName());
// or simply just
jo.addProperty("className", "Animal");
// Loop through the animal object's member variables and add them to the JO accordingly
return jo;
}
}
Then you need to instantiate a new Gson() object via GsonBuilder for the sake of attaching the serializers as desired:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Dog.class, new DogSerializer())
.registerTypeAdapter(Animal.class, new AnimalSerializer())
.create();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With