How to get array of objects with gson/retrofit? -
i have used gson before automatically convert pojo's.
but im trying use retrofit convert api result objects.
as long json has named arrays of objects no problem:
e.g.:
{ items:[ {"name":"foo"}, {"name":"bar"} ] } public class anitem { string name; } public class myitems { list<anitem> items; } public interface myapi { @get("/itemlist") call<myitems> loaditems(); } public boolean onoptionsitemselected(menuitem item) { retrofit retrofit = new retrofit.builder() .baseurl("https://someurl.com/api") .addconverterfactory(gsonconverterfactory.create()) .build(); myapi myapi = retrofit.create(myapi.class); call<myapi> call = myapi.loaditems(); call.enqueue(this); return true; } @override public void onresponse(response<myitems> response, retrofit retrofit) { arrayadapter<anitem> adapter = (arrayadapter<anitem>) getlistadapter(); adapter.clear(); adapter.addall(response.body().items); } this automatically work.
but how if json array isn't named?
e.g.:
[ {"name":"foo"}, {"name":"bar"} ] i know how when not using retrofit parsejson , iterate on array objects cant because part automated retrofit , gson.
ive been stuck on problem time , pointers appreciated..
update:
below parts have changed myitems list<anitem>: public class alltemplatesretroactivity extends listactivity implements callback<list<anitem>> { protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_indeterminate_progress); requestwindowfeature(window.feature_progress); arrayadapter<anitem> arrayadapter = new arrayadapter<anitem>(this, android.r.layout.simple_list_item_1, android.r.id.text1, new arraylist<anitem>()); setlistadapter(arrayadapter); } @override public boolean onoptionsitemselected(menuitem item) { retrofit retrofit = new retrofit.builder() .baseurl("https://someurl.com/api") .addconverterfactory(gsonconverterfactory.create()) .build(); myapi myapi = retrofit.create(myapi.class); call<list<anitem>> call = myapi.loaditems(); call.enqueue(this); return true; } @override public void onresponse(response<list<anitem>> response, retrofit retrofit) { arrayadapter<anitem> adapter = (arrayadapter<anitem>) getlistadapter(); adapter.clear(); log.i("##mylog###", "## response:"+ response.message()); adapter.addall(response.body()); }
to handle json response this:
[ {"name":"foo"}, {"name":"bar"} ] use call< list < anitem>>
in retrofit2, httpurl.resolve() used resolve baseurl , annotated path.
due how works,
this works:
.baseurl("http://someurl.com") @get("/api/itemlist") --> resolved http://someurl.com/api/itemlist or works
.baseurl("http://someurl.com/api/") @get("itemlist") ---> resolved http://someurl.com/api/itemlist however, not work
.baseurl("http://someurl.com/api") @get("/itemlist") ---> resolved http://someurl.com/itemlist
Comments
Post a Comment