javaspringspring-bootresttemplateobjectmapper

Generic List object mapper


I am trying to get a generic list from object mapper but it not retunning a type specific list.

    public <T,V> List<V> invokeService(T request, String url,Class<V> type) {

    HttpEntity requestEntity = new HttpEntity<>(sdsRequest, headers);
      ResponseEntity<String>  response= restTemplate.exchange(returnURI,HttpMethod.POST,requestEntity,String.class);

  ObjectMapper objectMapper=new ObjectMapper();
  ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<V>>(){});
  try {
    List<V> list = objectReader.readValue(response.getBody());
    log.info("returned value {}",list );
    return list;
  } catch (JsonProcessingException e) {
    throw new RuntimeException(e);
  }
}

Outout

returned value [{settlement_group_id=72, id=3142193, value=812954, code=GO}]

As we can see in the output. It is getting converted to List but not of a particular type.

Exception:

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.service.dtos.PartyMapResponseDTO (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.service.dtos.PartyMapResponseDTO is in unnamed module of loader 'app')

Solution

  • Solved this:

     private <T> List<T> getObjectList(final String json, final Class<T> cls) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        return objectMapper
                .readValue(json, objectMapper.getTypeFactory()
                        .constructCollectionType(ArrayList.class, cls));
      }
    
    List<V> objectList = getObjectList(response.getBody(), type);
    log.info("returned object new method {}", objectList);
    

    Log:

     returned object new method [PartyMapResponseDTO(id=31193, value=80954, settlement_group_id=72, code=GOL)]