Gson 自动添加类名

2022-09-04 19:58:18

假设我有以下类:

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的东西来实现?


答案 1

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

答案 2

为此,您将需要自定义序列化程序。下面是上面 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();

推荐