Java Generic Web Client

15 hours ago 4
ARTICLE AD BOX

I have multiple APIs that returns different response bodies. I want to have a generic service that is able deserialize any data to given type.

public class GenericResponse<T> { private T data; private String message; }

here T can be any dto.

and my generic service looks like this.

public RestService{ public <T> T getRestUrl(url){ return webClient .get() .uri(url) .headers(httpHeaders -> httpHeaders.addAll(getApiHeaders())) .retrieve() .onStatus(HttpStatusCode::isError, this::handleError) .bodyToMono(new ParameterizedTypeReference<T>() {}) .block(); } } GenericResponse<MyCustonDTO> response = restService.getRestUrl(urlWithParameters);

however when i run the query the response is not serialized to MyCustomDTO it is serialized to linkedHashMap since java is not able to determine what T is in the runtime.

Is there any workaround or any other way to achieve a generic rest service to remove code duplication every time i make a rest call.

Read Entire Article