本文介绍了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如下:

and I use resttemplate as follows:

...
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

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

有什么想法吗?

PS:我的错误是:

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

我认为 resttemplate 无法理解我的通用变量,也许它接受它作为对象而不是通用 T.所以它变成了 LinkedHashMap.你可以从它这里阅读它说,当从它的编组来解释时:

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 类型 |Java 类型

对象 |LinkedHashMap

object | LinkedHashMap

推荐答案

ParameterizedTypeReference 已在 3.2 M2 中引入以解决此问题.

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();

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

However, the postForObject/getForObject variant was not introduced.

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

08-01 05:26