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.
If your A
class is abstract RestTemplate
won't be able to instantiate it. There are possible solutions:
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. 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.