How to create a custom list deserializer in Gson?

I need to deserialize a Json file with an array. I know how to deserialize it to get a List object, but in the structure I use a custom list object that does not implement the Java List interface. My question is: how to write a deserializer for my custom list object?

EDIT: I want the deserializer to be universal, which means I want it to work for each list, for example CustomList<Integer> , CustomList<String> , CustomList<CustomModel> not only of a specific type of list, since that would be annoy make a deserializer for all kinds that i use.

+6
source share
1 answer

Here 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 as follows:

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

Source: https://habr.com/ru/post/1013688/


All Articles