Deserialización de listas / matrices genéricas Java gson

I'm trying to deserialize a generic list using Gson. I'm able to deserialize the following JSON:


con el siguiente código:

T[] array = (T[])java.lang.reflect.Array.newInstance(p_class, 0);
gson.fromJson(content, array.getClass());

But now, I have the following JSON what I can't figure out how to deserialize with gson:


Gracias por su ayuda!

preguntado el 09 de marzo de 12 a las 13:03

the strange thing is that using the same technique creates the 4 Brand model but all of their attributes are null -

Que es p_class en tu código? -

p_class is a simple Class object such as: Brand.class -

1 Respuestas

You need to create a new class which has an object named marca and is a type of p_class. Then use gson on your new class as you did before and it should return you an array of your new class. for example:

class Brand{
    private p_class brand;

    public p_class getBrand(){
        return brand;

and for gson:

List<Brand> brands = (List<Brand>) gson.fromJson(content, new TypeToken<List<Brand>>(){}.getType());

another way would be doing with 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 is your desired object
        p_class p = gson.fromJson(obj.getJSONObject("brand").toString(), p_class.class);

respondido 09 mar '12, 14:03

Is there a way that I can create these classes generically and automatically? I need to reserve this code as generic - seriakillaz

Your first solution can't be generalized, but your second one can be, so it's definetly a good answer, Thank You!! - seriakillaz

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.