使用 Spring RESTTemplate 的泛型

我有一门这样的课:

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;
}


}

我使用 resttemplate 如下:

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

然而,它抛出了一个:

ClassCastException

我读了: 试图在 Java 中使用 Jackson 时出现问题,但没有帮助。有一些话题与我的问题等: https://jira.springsource.org/browse/SPR-7002https://jira.springsource.org/browse/SPR-7023

有什么想法吗?

PS: 我的错误是:

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

我认为 resttemplate 无法理解我的泛型变量,也许它接受它作为一个 Object 而不是泛型 T。所以它变成了 LinkedHashMap。你可以从它读 给你它说,当解释从什么它汇编到:

JSON 类型 | Java 类型

对象 | LinkedHashMap

72062 次浏览

Do not use generics with RestTemplate. Wrap request and response object with wrapper object that will hide the generics.

ParameterizedTypeReference has been introduced in 3.2 M2 to workaround this issue.

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

However, the postForObject/getForObject variant was not introduced.

The only thing I think you could do is creating a new class that extends Wrapper and uses model as a generic.

class WrapperWithModel extends Wrapper<Model>{};


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

It's not the best solution, but at least you won't have to unmarshall manually the response.