Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a custom list deserializer in Gson?

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.

like image 666
BananyaDev Avatar asked Jan 01 '17 19:01

BananyaDev


People also ask

How do you deserialize with Gson?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished. Program output.

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

What does Gson toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.


1 Answers

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();
like image 58
Egor Neliuba Avatar answered Sep 19 '22 15:09

Egor Neliuba