Generics con el resto de la primavera


Tengo una clase así:

public class Wrapper<T> {

 private String message;
 private T data;

 public String getMessage() {
    return message;
 }

 public void setMessage(String message) {
    this.message = message;
 }

 public T getData() {
    return data;
 }

 public void setData(T data) {
    this.data = data;
 }

}

Y uso resttemplate de la siguiente manera:

...
Wrapper<Model> response = restTemplate.getForObject(URL, Wrapper.class, myMap);
Model model = response.getData();
...

Sin Embargo, lanza un:

ClassCastException

Leí que: Problema al intentar usar Jackson en java pero no ayudó. Hay algunos temas relacionados con mi problema etc.: https://jira.springsource.org/browse/SPR-7002 y https://jira.springsource.org/browse/SPR-7023

¿Alguna idea?

PS: Mi error es que:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to a.b.c.d.Model

Creo que resttemplate no puede entender mi variable genérica y tal vez la acepta como un Objeto en lugar de genérica T. Por lo que se convierte en un LinkedHashMap. Puedes leer de él aquí Dice que cuando se explica de lo que marshalls a:

Tipo JSON / Tipo Java

Object / LinkedHashMap

Author: Community, 2011-11-13

4 answers

ParameterizedTypeReference se ha introducido en 3.2 M2 para solucionar este problema.

Wrapper<Model> response = restClient.exchange(loginUrl, 
                          HttpMethod.GET, 
                          null, 
                          new ParameterizedTypeReference<Wrapper<Model>>() {}).getBody();

Sin embargo, la variante postForObject/getForObject no se introdujo.

 84
Author: Manimaran Selvan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 09:44:59

Lo único que creo que podría hacer es crear una nueva clase que extienda Wrapper y use model como genérico.

class WrapperWithModel extends Wrapper<Model>{};

WrapperWithModel response = restTemplate.getForObject(URL, WrapperWithModel.class);

No es la mejor solución, pero al menos no tendrá que desmarcar manualmente la respuesta.

 4
Author: Juan Luis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-22 16:53:00

No utilice genéricos con RestTemplate. Wrap request and response object con wrapper object que ocultará los genéricos.

 3
Author: Dima,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-19 13:17:53

No necesitas ni un envoltorio para esto. Prueba esto.

/**
 * 
 * Method for GET Operations
 * 
 * @param url url to send request
 * @return returned json String
 * @throws Exception exception thrown
 */
public List<T> getJSONString(String url, Class<T[]> clazz) throws Exception {

    logger.debug("getJSONString() : Start");

    List<T> response = null;

    ResponseEntity<T[]> responseEntity = null;

    List<String> hostList = Arrays.asList(propertyFileReader.getRestApiHostList().split("\\s*,\\s*"));

    Iterator<String> hostListIter = hostList.iterator();

    String host = null;

    while (true) {
        try {
            host = hostListIter.next();

            logger.debug("getJSONString() : url={}", (host + url));
            responseEntity = restTemplate.getForEntity(host + url, clazz);
            if (responseEntity != null) {
                response = Arrays.asList(responseEntity.getBody());
                break;
            }
        } catch (RestClientException ex) {
            if (!hostListIter.hasNext()) {
                throw ex;
            }
            logger.debug("getJSONString() : I/O exception {} occurs when processing url={} ", ex.getMessage(),
                    (host + url));
        }
    }

    return response;
}
 0
Author: Khader M A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-27 12:12:23