13

可以说我有以下课程:

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 实现?

4

2 回答 2

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));
于 2012-08-24T23:15:22.113 回答
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();
于 2012-08-24T22:15:33.630 回答