2

I'm trying to return a ResponseEntity list and casting that response respect to my model classes.

For instance: if I use ResponseEntity<List<ApplicationModel>> it's working well but I do not want to write a response method per model.

ResponseEntity method

    public static <T> ResponseEntity<List<T>> getResponseList(String resourceURL) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<List<T>> entity = new HttpEntity<List<T>>(headers);
    ResponseEntity<List<T>> response = restTemplate.exchange(resourceURL, HttpMethod.GET, entity,
            new ParameterizedTypeReference<List<T>>() {
            }, Collections.emptyMap());

    return response;
}

Method call

    private final String url ="http://localhost:8090/xxx/application";

    ResponseEntity<List<ApplicationModel> responseForApplications =
 ResponseTemplate.getResponseList(url);

    if (responseForApplications.getStatusCode() == HttpStatus.OK) 
         List<ApplicationModel> dtoApplications = responseForApplications.getBody();

Example of JSON response which I want to cast

{"id":1,"name":"foo","description":"foo"}

Error

There was an unexpected error (type=Internal Server Error, status=500). Error creating bean with name 'index': Invocation of init method failed; nested exception is java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xxx.ApplicationModel

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
Emre
  • 67
  • 1
  • 2
  • 11

2 Answers2

2

The issue's coming from Jackson. When it doesn't have enough information on what class to deserialize to, it uses LinkedHashMap.

Since you're not informing Jackson of the element type of your ArrayList, it doesn't know that you want to deserialize into an ArrayList of ApplicationModels. So it falls back to the default.

Instead, you could probably use as(JsonNode.class), and then deal with the ObjectMapper in a richer manner than rest-assured allows.

Please refer to java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account for additional information.

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
2

Using mapper.convertValue works for me.

ObjectMapper mapper = new ObjectMapper();
List<ApplicationModel> dtoApplications = mapper.convertValue(responseForApproles.getBody(), new TypeReference<List<ApplicationModel>>() {});
Emre
  • 67
  • 1
  • 2
  • 11