Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring WebClient with ParameterizedTypeReference doesn't work

I have a Spring Boot application and I'm using WebClient to make requests to an API that returns the following format {"results": {...}} where the object in the results field can be in multiple different formats. I created the following class to store the API response.

@Data
@Jacksonized
@Builder
public class ApiResponse<T> {
    private T results;
}

When I call the following method:

public MyResClass makeApiCall(String URI) {
    ApiResponse<MyResClass> response = webClient.get()
                    .uri(URI)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .bodyToMono(new ParameterizedTypeReference<ApiResponse<MyResClass>>() {})
                    .block();

    return response.getResults();
}

a java.lang.ClassCastException is thrown with the message: "class java.util.LinkedHashMap cannot be cast to class MyResClass"

like image 701
k.kolev Avatar asked Sep 10 '25 05:09

k.kolev


1 Answers

Delete the @Builder and @Jacksonized annotations and repeat the tests, seems to be working fine without them.

P.S. be careful about the block() call, if this code happens to be executed on a Non-Blocking thread all sorts of errors could be thrown!

like image 150
Domenico Sibilio Avatar answered Sep 12 '25 18:09

Domenico Sibilio