本文介绍了如何在Gson中制作自定义列表反序列化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要反序列化具有数组的Json文件.我知道如何反序列化它,以便获得List对象,但是在框架中,我使用的是自定义列表对象,该对象未实现Java List接口.我的问题是,如何为自定义列表对象编写反序列化器?

I need to deserialize a Json file that has an array. I know how to deserialize it so that I get a List object, but in the framework I am using a custom list object that does not implement the Java List interface. My question is, how do I write a deserializer for my custom list object?

我希望解串器具有通用性,这意味着我希望它对每种类型的列表都有效,例如CustomList<Integer>CustomList<String>CustomList<CustomModel>不仅适用于特定类型的列表,因为它会很烦人使我使用的每种类型的解串器.

I want the deserializer to be universal, meaning that I want it ot work for every kind of list, like CustomList<Integer>, CustomList<String>, CustomList<CustomModel> not just a specific kind of list since it would be annoying to make deserializer for every kind I use.

推荐答案

这是我想出的:

class CustomListConverter implements JsonDeserializer<CustomList<?>> {
    public CustomList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
        Type valueType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];

        CustomList<Object> list = new CustomList<Object>();
        for (JsonElement item : json.getAsJsonArray()) {
            list.add(ctx.deserialize(item, valueType));
        }
        return list;
    }
}

像这样注册:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(CustomList.class, new CustomListConverter())
        .create();

这篇关于如何在Gson中制作自定义列表反序列化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:17