How to read JSON to a list of generic objects in java? -
i have data web service, i'm using jackson have same problem using gson, have no problem single objects when receive several objects list not easy me.
json received this:
{"country": [ {"code":"ad","nombre":"andorra","name":"andorra"}, {"code":"ae","nombre":"emiratos Árabes unidos","name":"united arab emirates"} ] }
this list of own class countrywstype
, have several classes , need way can list of type of them. i've tried parse list:
list<myclass> myobjects = mapper.readvalue(jsoninput, mapper.gettypefactory().constructcollectiontype(list.class, myclass.class));
also trying creating own list type:
public class listwstype<t> implements list<t>{ private list<t> listainterna; //implents methods }
but jsonmappingexception
, have no more ideas of how it.
i hope can me.
as people ask here class trying parse json:
@xmlrootelement(name="country") @xmltype(proporder={"code", "nombre", "name"}) public class countrywstype { /** código iso */ @xmlelement(name="code") public string code; /** nombre en español */ @xmlelement(name="nombre") public string nombre; /** nombre en inglés */ @xmlelement(name="name") public string name; /** constructor sin parámetros. no inicializa nada... * está para que funcione el marshall/unmarshall. */ public countrywstype() {} }
also notice when put myclass means countrywstype class, sorry missunderstood.
may help:
//first convert input string json array jsonobject jsonobject = new jsonobject(countriesasjsonstring); jsonarray jsonarray = jsnobject.getjsonarray("countries"); //then type list , parse using gson type listtype = new typetoken<list<myclass>>(){}.gettype(); list<myclass> countrieslist = new gson().fromjson(jsonarray, listtype);
if saying json arrary elements can of different types, mapper not know type of class instantiate , need supply additional attribute in json indicate that, ugly approach specially if json external facing. if want explained in this post.
Comments
Post a Comment