DEV Community

André Moriya
André Moriya

Posted on

ObjectMapper: Conversion to generic types.

Hey folks!

I decided to write this post because I needed to do a conversion using generic classes.

It's quite simple, but I believe that it can be helpful in the future, both for myself and for other devs.

What I was needed to get a JSON callback coming from a rest service, developed in the company.

The code looks like this:

CloseableHttpClient client = HttpClients.createDefault();

// Code omitted...
response = client.execute(request);
// Code omitted...

BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
ResponseApiDTO<ProductDTO> response = mapper.readValue(br.readLine(), new TypeReference<ResponseApiDTO<ProductDTO>>() {});

ProductDTO dto = response.getDto();
Enter fullscreen mode Exit fullscreen mode

That was basically it.
As the project doesn't use spring, this was the way implemented.

Well, that's it, I hope this post could have helped.

Thanks

Latest comments (0)