To parse some webservice results I have a java bean that Jackson can parse like this:
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(in, ResultPage.class);
Now inside my ResultPage, amongst other data I have a list of results (the payload I am after). Depending on the query that delivers the result, the type of listed documents can vary (Documents, Tags, Keywords, ...) but the general list format does not vary. Thus I made my ResultPage bean a generic type that contains a list of results like so:
public class ResultPage<T> {
...
private List<T> results;
...
}
As a next step I'd have to call the parser while providing this type, and I am getting lost at
public <T> ResultPage<T> parseResultPage(InputStream in, Class<T> valueType) throws IOException {
return mapper.readValue(in, ResultPage<valueType>.class);
}
Also this (seemingly simpler attempt) does not compile for me:
ResultPage<Tag> rp = mapper.readValue(responseEntity.getContent(), ResultPage<Tag>.class);
How could I make such a setup work?
Use TypeReference
:
public <T> ResultPage<T> parseResultPage(String content, Class<T> resultType) throws IOException {
TypeReference<ResultPage<T>> typeRef = new TypeReference<>() {};
return new ObjectMapper().readValue(in, typeRef);
}