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.

Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77
BananyaDev
  • 583
  • 5
  • 13
  • 2
    Why don't you deserialize it first with Java class first and then write your own transformer to the custom list object? – Reaz Murshed Jan 01 '17 at 19:09
  • Have a look at [this](http://stackoverflow.com/questions/16590377/custom-json-deserializer-using-gson) –  Jan 01 '17 at 19:12
  • @ReazMurshed I could do that but I am deserializing it into an object model that I then use in the rest of my code. I could make a ModelJson class and a Model class where the ModelJson one uses the List interface from Java and is only used for deserialization, converting it after to the Model class. The problem with this is that I have a lot classes that do that so it's a bit of a pain and also I am curious as to whether or not there is a more elegant solution. If there is not I will go down the hard coding path but I wish I wouldn't have to. – BananyaDev Jan 01 '17 at 19:16
  • @SzymonD the problem with that answer is that I need to make a general deserializer for my list. I need it to deserialize any king of list, as in CustomList, CustomList, CustomList, etc. In the aswer that you gave the OP knew exactly the type of data that he needed to deserialize. I know how to deserialize a custom model, I was just curious how to do it for a custom list, if it is possible. – BananyaDev Jan 01 '17 at 19:20

1 Answers1

5

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();
Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77