Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson automatically add classname

Tags:

java

gson

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?

like image 205
user1051218 Avatar asked Aug 23 '12 18:08

user1051218


2 Answers

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));
like image 198
Jesse Wilson Avatar answered Sep 19 '22 21:09

Jesse Wilson


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();
like image 22
Ankit Aggarwal Avatar answered Sep 20 '22 21:09

Ankit Aggarwal