How can I receive a Map<String, Integer> from an endpoint web service using WebClient in Spring Boot? Here is my try: (it gives syntax error: Incompatible equality constraint: Map<String, Integer> and Map). How can I fix it?
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(Map.class);
}
For generic types, like the Map, you should use ParameterizedTypeReference instead of a class in the call to the bodyToFlux method:
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<>() {});
}
In practice, probably you would like to define a constant for the type reference:
private static final ParameterizedTypeReference<Map<String, Integer>> MAP_TYPE_REF = new ParameterizedTypeReference<>() {};
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(MAP_TYPE_REF);
}
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