Gson自动添加classname

时间:2012-08-23 18:27:13

标签: java gson

假设我有以下课程:

public class Dog {
    public String name = "Edvard";
}

public class Animal {
    public Dog madDog = new Dog();
}

如果我通过Gson运行它,它会将其序列化如下:

GSon gson = new GSon();
String json = gson.toJson(new Animal())

result:
{
   "madDog" : {
       "name":"Edvard"
   }
}

这非常好,但是我想用Gson自动为所有类添加className,所以我得到以下结果:

{
   "madDog" : {
       "name":"Edvard",
       "className":"Dog"
   },
   "className" : "Animal"
}

有人知道某种拦截器或Gson有什么可能吗?

2 个答案:

答案 0 :(得分:16)

看看这个: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));

答案 1 :(得分:3)

您需要自定义序列化程序。以下是上面Animal类的示例:

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;
    }
}

然后你需要通过GsonBuilder实例化一个新的Gson()对象,以便根据需要附加序列化器:

Gson gson = new GsonBuilder()
    .registerTypeAdapter(Dog.class, new DogSerializer())
    .registerTypeAdapter(Animal.class, new AnimalSerializer())
    .create();