3

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"

k.kolev
  • 83
  • 1
  • 7

1 Answers1

7

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!

Domenico Sibilio
  • 1,189
  • 1
  • 7
  • 20
  • 2
    Yep, that did it. I thought I needed those annotations for it to work with Jackson, but it works fine this way. – k.kolev Feb 13 '21 at 20:08
  • 3
    "P.S. using block() is utterly bad". That really depends on where you use this webclient. Sure if its part of a webflux reactive stream its bad, if you are using just using webclient in your blocking application because it has nice features, blocking is totally fine. It's even the recommended way to start with webflux by (at least one of) the guys that build it. – p.streef Feb 13 '21 at 20:41