简体   繁体   English

Gson具有静态类型或运行时类型

[英]Gson with static type, or runtime type

I am serializing a class from a hierarchy with Gson, and this is my proof-of-concept code: 我正在使用Gson从层次结构中序列化一个类,这是我的概念验证代码:

import com.google.gson.Gson;

class A {
    public String aField;
}

class B extends A {
    public String bField;
}

class Main {
    static public void main(String[] args) {
        B b = new B();
        b.aField = "field from a";
        b.bField = "field from b";
        A a = b;
        Gson gson = new Gson();
        System.out.println(gson.toJson(a));
    }
}

with prints out: 打印出:

{"bField":"field from b","aField":"field from a"}

So we can see Gson uses the fields from the dynamic type of the object its going to serialize (class B). 因此,我们可以看到Gson使用了要序列化的对象的动态类型的字段(类B)。 But. 但。 Is there a way to make Gson use the static type of the object (class A)? 有没有办法让Gson使用对象的静态类型(类A)? I want to get someting like 我想要点东西

{"aField":"field from a"}

Thanks. 谢谢。

As @njzk2 posted, I have to use toJson(Object src, Type srcType) with A's class like in gson.toJson(a, A.class) . 正如@ n​​jzk2发布的那样,我必须将toJson(Object src, Type srcType)与A的类一起使用,例如gson.toJson(a, A.class)

For the other folks who didn't see this little detail like me: 对于其他没有像我这样细小的细节的人:

You have to use A.class, and not a.getClass(). 您必须使用A.class,而不是a.getClass()。 the former is an identifier of any class, but the latter returns, as the documentation says, the runtime class of the object. 前者是任何类的标识符,但是后者(如文档所述)返回对象的运行时类。

Thanks @njzk2. 谢谢@ njzk2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM