Search code examples
javaspringspring-bootjacksonspring-webclient

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"


Solution

  • 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!