java - Gson with static type, or runtime type -


i serializing class hierarchy gson, , proof-of-concept code:

import com.google.gson.gson;  class {     public string afield; }  class b extends {     public string bfield; }  class main {     static public void main(string[] args) {         b b = new b();         b.afield = "field a";         b.bfield = "field b";         a = b;         gson gson = new gson();         system.out.println(gson.tojson(a));     } } 

with prints out:

{"bfield":"field b","afield":"field a"} 

so can see gson uses fields dynamic type of object going serialize (class b). but. there way make gson use static type of object (class a)? want someting like

{"afield":"field a"} 

thanks.

as @njzk2 posted, have use tojson(object src, type srctype) a's class in gson.tojson(a, a.class).

for other folks didn't see little detail me:

you have use a.class, , not a.getclass(). former identifier of class, latter returns, documentation says, runtime class of object.

thanks @njzk2.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -