json - Deserialize type extending abstract class in GSON -
json - Deserialize type extending abstract class in GSON -
i want serialize/deserialize array of objects extend abstract object using gson. made typehierarchyadapter this:
private static class basemodeladapter<t extends basemodel> implements jsonserializer<t>, jsondeserializer<t>{ private static final string model_type_property = "model_type_property"; private static final string children_property = "children"; private static final gson gson = new gson(); @override public t deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { if(!json.getasjsonobject().has(model_type_property)) { throw new jsonparseexception("couldn't find target class! \n" + json.tostring()); } final string classname = json.getasjsonobject().get(model_type_property).getasstring(); seek { homecoming (t) gson.fromjson(json, class.forname(classname)); } grab (classnotfoundexception e) { log.e(tag, e); throw new jsonparseexception("couldn't find target class!", e); } } @override public jsonelement serialize(t src, type typeofsrc, jsonserializationcontext context) { final jsonobject ret = gson.tojsontree(src).getasjsonobject(); ret.add(children_property, context.serialize(src.getchildren())); ret.addproperty(model_type_property, src.getclass().getname()); homecoming ret; } } this utilize adapter this:
typetoken<list<basemodel>> typetoken = new typetoken<list<basemodel>>(){}; gsonbuilder builder = new gsonbuilder(); builder.registertypehierarchyadapter(basemodel.class, new basemodeladapter<basemodel>()); builder.setprettyprinting(); gson special = builder.create(); string json = special.tojson(featured); //works! list<basemodel> basemodels = special.fromjson(json, typetoken.gettype()); //exception thrown! it works if create basemodel not abstract, suppose sake of making work. much rather maintain basemodel abstract should be. exception thrown says can not invoke no-args constructor has never been problem gson before. adding no-args constructor basemodel class not prepare problem , still says same message. there anyway can work while keeping basemodel abstract?
json gson abstract-class
Comments
Post a Comment