2

I have an Abstract base class A, and 2 subclasses (B and C) inherit from A.

Now I am currently using RestTemplate exchange to retrieve a list of objects from a REST API endpoint. But those objects can be either B or C. How do I do this using RestTemplate? The following if my code

ResponseEntity<B> response = restTemplate.exchange(
                endpointURL,
                HttpMethod.GET,
                request,
                new ParameterizedTypeReference<B>() {} );

Above is for B, but the responseEntity can be either B or C.

  • Maybe you are looking for this? https://stackoverflow.com/questions/21987295/using-spring-resttemplate-in-generic-method-with-generic-parameter/29547365#29547365 – Estevao Santiago Jul 23 '19 at 18:47
  • Use `A` as a response entity, Maybe, Also remember that RestTemblate is deprecated use `WebClient` instead https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html – Youans Jul 23 '19 at 18:47
  • @YouYou ahh, didnt know it was deprecated, thanks for the notice! – user11826426 Jul 23 '19 at 21:29

1 Answers1

0

If your A class is abstract RestTemplate won't be able to instantiate it. There are possible solutions:

  • Make A not abstract. You will be able to get A instance as a response but all of the B and C specific fields will be missed.
  • Use String or Jackson's JsonNode as a response type and then manually check the properties to make sure that response is B or C and create your B/C instance using Jackson's ObjectMapper.
Sergiy Dakhniy
  • 538
  • 1
  • 4
  • 15