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:

[{"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"}]

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:

[{"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"}}]

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.