android - Java gson generic array/list deserialization -
i'm trying deserialize generic list using gson. i'm able deserialize following json:
[{"updated_at":"2012-03-09t11:13:31z","id":1,"title":"moda","position":0,"short_name":"md"}, {"updated_at":"2012-03-09t11:13:40z","id":2,"title":"sissi","position":1,"short_name":"si"}, {"updated_at":"2012-03-09t11:13:47z","id":3,"title":"levis","position":2,"short_name":"lv"}, {"updated_at":"2012-03-09t11:14:03z","id":4,"title":"dolce&gabanna","position":3,"short_name":"dg"}]
with following code:
t[] array = (t[])java.lang.reflect.array.newinstance(p_class, 0); gson.fromjson(content, array.getclass());
but now, have following json can't figure out how deserialize gson:
[{"brand":{"updated_at":"2012-03-09t11:13:31z","id":1,"title":"moda","position":0,"short_name":"md"}}, {"brand":{"updated_at":"2012-03-09t11:13:40z","id":2,"title":"sissi","position":1,"short_name":"si"}}, {"brand":{"updated_at":"2012-03-09t11:13:47z","id":3,"title":"levis","position":2,"short_name":"lv"}}, {"brand":{"updated_at":"2012-03-09t11:14:03z","id":4,"title":"dolce&gabanna","position":3,"short_name":"dg"}}]
thanks help!
you need create new class has object named brand , type of p_class. use gson on new class did before , should return array of new class. example:
class brand{ private p_class brand; public p_class getbrand(){ return brand; } }
and gson:
list<brand> brands = (list<brand>) gson.fromjson(content, new typetoken<list<brand>>(){}.gettype());
another way doing ordinary json objects available in android framework:
jsonarray ar = new jsonarray(content); for(int i=0; i<ar.length(); i++){ jsonobject obj = ar.getjsonobject(i); //here desired object p_class p = gson.fromjson(obj.getjsonobject("brand").tostring(), p_class.class); }
Comments
Post a Comment