本文介绍了Gson自动添加classname的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有以下类:

Lets say I have the following classes:

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

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

如果我通过Gson运行它,它会按如下方式序列化它: p>

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

这很好,但我想已经为Gson自动添加了所有类的className,所以我得到了以下结果:

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

有人知道这是否可以用某种拦截器或Gson的东西?

Does anyone know if this is possible with some kind of interceptors or something with Gson?

推荐答案

请看这个:

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

这篇关于Gson自动添加classname的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:31