java - How do I implement TypeAdapterFactory in Gson? -
how implement type typeadapterfactory in gson?
the main method of create generic. why?
the registration method registertypeadapterfactory() not receive type type argument. so, how gson know classes processed factory?
should implement 1 factory multiple classes, or can implement 1 many classes?
if implement 1 factory multiple classes, should return in case of out-of-domain type argument?
when register regular type adapter (gsonbuilder.registertypeadapter), generates type adapter specific class. example:
public abstract class animal { abstract void speak(); } public class dog extends animal { private final string speech = "woof"; public void speak() { system.out.println(speech); } } // in gson related method gsonbuilder.registertypeadapter(animal.class, mytypeadapterobject); gson g = gsonbuilder.create(); dog dog = new dog(); system.out.println(g.tojson(dog)); if did this, gson not use mytypeadapterobject, use default type adapter object.
so, how can make type adapter object can convert animal subclass json? create typeadapterfactory! factory can match using generic type , typetoken class. should return null if typeadapterfactory doesn't know how handle object of type.
the other thing typeadapterfactory can used can't chain adapters other way. default, gson doesn't pass gson instance read or write methods of typeadapter. if have object like:
public class myouterclass { private myinnerclass inner; } there no way write typeadapter<myouterclass> knows how use typeadapter<myinnerclass> without using typeadapterfactory. typeadapterfactory.create method pass gson instance, allows teach typeadapter<myouterclass> how serialize myinnerclass field.
generally, here standard way begin write implementation of typeadapterfactory:
public enum fooadapterfactory implements typeadapterfactory { instance; // josh bloch's enum singleton pattern @suppresswarnings("unchecked") @override public <t> typeadapter<t> create(gson gson, typetoken<t> type) { if (!foo.class.isassignablefrom(type.getrawtype())) return null; // note: have access `gson` object here; can access other deserializers using gson.getadapter , pass them constructor return (typeadapter<t>) new fooadapter(); } private static class fooadapter extends typeadapter<foo> { @override public void write(jsonwriter out, foo value) { // code } @override public foo read(jsonreader in) throws ioexception { // code } } }
Comments
Post a Comment