java - Gson custom deserializer for generic types -
i have number of classes implement single interface type. want write custom deserializer able handle special case json have deserialize. possible google gson? here sample code have far:
class type:
public class myclass implements myinterface { ....... } deserializer
public class responsedeserializer implements jsondeserializer<myinterface> { private gson fgson; public responsedeserializer() { fgson = new gson(); } @override public myinterface deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { string jsonstring = json.tostring(); if(jsonstring.substring(0, 0).equals("[")) { jsonstring = "{ \"parameter\":" + jsonstring + "}"; } return context.deserialize(json, typeoft); } } register , call fromjson method:
@override public <t extends myinterface> t createresponse(class<t> responsetype) { t returnobject = new gsonbuilder().registertypeadapter(myinterface.class, new responsedeserializer()) .create().fromjson(getentitytext(), responsetype); return returnobject; } thanks in advance
first of all, registertypeadapter() not covariant; if want link typeadapter interface, have use typeadapterfactory. see: how implement typeadapterfactory in gson?
secondly, why think [{...},{...},{...}] not valid json? of course is:
{ "foo":[ { "type":"bar" }, { "type":"baz" } ] } this mapping of key foo array of objects, 1 member variable. gson automatically deserialize following pojos:
public class myobject { list<typedobject> foo; } public class typedobject { string type; } beyond that, can't more without knowing specific json string. (especially first link) should enough started, however.
Comments
Post a Comment