Reputation: 328
So I've got these 2 Methods:
private List<Song> toSongList(String json) {
ObjectMapper mapper = new ObjectMapper();
List<Song> list = null;
list = mapper.readValue(json, mapper.getTypeFactory()
.constructCollectionType(List.class, Song.class));
return list;
}
private List<Interpreter> toInterpreterList(String json) {
ObjectMapper mapper = new ObjectMapper();
List<Interpreter> list = null;
list = mapper.readValue(json, mapper.getTypeFactory()
.constructCollectionType(List.class, Interpreter.class));
return list;
}
which I call with:
List<Song>songs = toSongList(jsonS);
List<Interpreter>interpreter = toInterpreterList(jsonI);
But I want to have a single Method, which I can call like this:
List<Song>songs = toList(Song.class, jsonS);
List<Interpreter>interpreter = toList(Interpreter.class, jsonI);
How can I achieve this?
Upvotes: 1
Views: 97
Reputation: 100209
This should work:
private <T> List<T> toList(Class<T> clazz, String json) {
ObjectMapper mapper = new ObjectMapper();
List<T> list = mapper.readValue(json, mapper.getTypeFactory()
.constructCollectionType(List.class, clazz));
return list;
}
Upvotes: 3