seriakillaz
seriakillaz

Reputation: 843

Java gson generic array/list deserialization

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

with the following code:

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

Thanks for your help!

Upvotes: 0

Views: 5139

Answers (1)

waqaslam
waqaslam

Reputation: 68177

You need to create a new class which has an object named brand 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);
    }

Upvotes: 4

Related Questions