I need to convert a Json array represented as String to List<Pojo>
using Jackson's ObjectMapper.
Here is what I did which doesn't really work:
public static <T> List<T> toList(String jsonString, Class<T> clazzType) {
try {
List<T> list = OBJECT_MAPPER.readValue(jsonString, new TypeReference<List<T>>() {});
return list;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
It returns an object with an internal list but doesn't really build the expected list of Pojos. I saw some attempts to use Reflection but I'm trying to keep it pure Jackson.
Any idea??
You can use the TypeFactory to create a CollectionLikeType. For example like this:
ObjectMapper objectMapper = new ObjectMapper();
CollectionLikeType collectionLikeType = objectMapper.getTypeFactory()
.constructCollectionLikeType(List.class, String.class);
List<String> o = objectMapper.readValue("[\"hello\"]", collectionLikeType);
assertEquals(o, List.of("hello"));