I am trying to build a generic class that will consume a REST api. The api returns lists of objects depending on the url.
I have built a Generic class
public class RestConsumer<T> {
WebClient client;
public RestConsumer(){
//Initialize client
}
public List<T> getList(String relativeUrl){
try{
return client
.get()
.uri(relativeUrl)
.retrieve()
.bodyToMono(new ParameterizeTypeReference<List<T>> (){}
.block()
catch(Exception e){}
}
}
The problem is that T is replaced by Object at compilation time and the whole thing return a List of LinkedHashMap instead of a List of T. I tried lots of workarounds but no luck. Any suggestions?
WebFlux client and server rely on the same non-blocking codecs to encode and decode request and response content. Internally WebClient delegates to an HTTP client library.
Overview Spring WebFlux is part of Spring 5 and provides reactive programming support for web applications. In this tutorial, we'll be creating a small reactive REST application using the reactive web components RestController and WebClient. We will also be looking at how to secure our reactive endpoints using Spring Security.
Other than Reactive RestController and WebClient, the WebFlux framework also supports reactive WebSocket and the corresponding WebSocketClient for socket style streaming of Reactive Streams. For more information, we also have a detailed article focused on working with Reactive WebSocket with Spring 5.
A lot of frameworks and projects are introducing reactive programming and asynchronous request handling. Consequently, Spring 5 introduced a reactive WebClient implementation as a part of the WebFlux framework. In this tutorial, we'll see how to reactively consume REST API endpoints with WebClient.
I encountered the same problem and in order to work I added ParameterizedTypeReference as a parameter for that function.
public <T> List<T> getList(String relativeUrl,
ParameterizedTypeReference<List<T>> typeReference){
try{
return client
.get()
.uri(relativeUrl)
.retrieve()
.bodyToMono(typeReference)
.block();
} catch(Exception e){
return null;
}
}
And call that function with
ParameterizedTypeReference<List<MyClass>> typeReference = new ParameterizedTypeReference<List<MyClass>>(){};
List<MyClass> strings = getList(relativeUrl, typeReference);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With