How to make a custom list deserializer in Gson?

2020-08-26 04:10发布

问题:

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?

EDIT: 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.

回答1:

This is what I came up with:

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

Register it like this:

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