泛型与Spring REST模板 [英] Generics with Spring RESTTemplate

查看:253
本文介绍了泛型与Spring REST模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个类:

  public class Wrapper< T> {

私人字符串消息;
私人T数据;

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-7002 https://jira.springsource.org/browse/SPR-7023



任何想法?



PS:我的错误是:

  java.lang.ClassCastException:java.util.LinkedHashMap不能转换为abcdModel 

我认为resttemplate无法理解我的泛型变量,也许它将它接受为Object而不是泛型T.因此它变成了LinkedHashMap。您可以从此处进行阅读它说,从什么时候解释到:


JSON类型| Java类型



object | LinkedHashMap



解决方案

3.2 M2中引入了ParameterizedTypeReference来解决此问题。

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

但是,postForObject / getForObject变体没有引入。


I have a class like that:

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

}

and I use resttemplate as follows:

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

However it throws a:

ClassCastException

I read that: Issue when trying to use Jackson in java but didn't help. There are some topics related to my problem etc.: https://jira.springsource.org/browse/SPR-7002 and https://jira.springsource.org/browse/SPR-7023

Any ideas?

PS: My error is that:

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

I think resttemplate can not understand my generic variable and maybe it accepts it as an Object instead of generic T. So it becomes a LinkedHashMap. You can read from it here It says that when explaining from what it marshalls to:

JSON Type | Java Type

object | LinkedHashMap

解决方案

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.

这篇关于泛型与Spring REST模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆