Java gson通用数组/列表反序列化

时间:2012-03-09 13:52:51

标签: java android json deserialization gson

我正在尝试使用Gson反序列化通用列表。 我能够反序列化以下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"}]

使用以下代码:

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

但是现在,我有以下JSON,我无法弄清楚如何使用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"}}]

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

您需要创建一个新类,其中包含名为品牌的对象,并且是 p_class 的类型。然后像以前一样在新类上使用gson,它应该返回一个新类的数组。例如:

class Brand{
    private p_class brand;

    public p_class getBrand(){
        return brand;
    }
}

和gson:

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

另一种方法是使用android框架中可用的普通json对象:

    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);
    }