简体   繁体   中英

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:

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). But. Is there a way to make Gson use the static type of the object (class 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) .

For the other folks who didn't see this little detail like me:

You have to use A.class, and not 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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