restTemplate.getForEntity 怎么返回匹配 ResponseEntity<List<Payment>> 的类型对象

2020-06-15 18:21:55 +08:00
 Vimax

我想返回ResponseEntity<List<Payment>>的格式类型,如何在保持泛型的同时List<Payment>,使用restTemplate.getForEntity返回正确的数据类型。

下面的代码是错误的,不兼容的返回类型:

  @GetMapping
    public ResponseEntity<List<Payment>> getPayment(Payment payment) {
        return restTemplate.getForEntity(SERVERURL + "/payment", List.class);
    }

提示信息:

Required type:
ResponseEntity <List<Payment>>

Provided:
ResponseEntity<List>

Incompatible equality constraint: List<Payment> and List

将返回类型去掉泛型,返回类型为 ResponseEntity<List>,可以解决兼容问题并返回数据。

  @GetMapping
    public ResponseEntity<List> getPayment(Payment payment) {
        return restTemplate.getForEntity(SERVERURL + "/payment", List.class);
    }

但是如何做,才能返回类型匹配 ResponseEntity<List<Payment>>。

  @GetMapping
    public ResponseEntity<List<Payment>> getPayment(Payment payment) {
        List<Payment> list = new ArrayList<>();
        return restTemplate.getForEntity(SERVERURL + "/payment", list.getClass());
    }
   

错误提示:

Required type:
ResponseEntity <List<Payment>>
Provided:
ResponseEntity <capture of ? extends List>
Incompatible equality constraint: List<Payment> and capture of ? extends List
2305 次点击
所在节点    Java
8 条回复
chendy
2020-06-15 19:00:00 +08:00
写一个 public class X extens ArrayList<Payment> ,然后参数里放 X.class
或者用 ParameterizedTypeReference<List<Payment>>,但是有点长而且只能用 exchange
nthin0
2020-06-15 19:06:23 +08:00
restTemplate.exchange(requestEntity, new ParameterizedTypeReference<List<Payment>>() {});
Vimax
2020-06-15 19:45:59 +08:00
@chendy 谢谢提供两种思路,采纳。
Vimax
2020-06-15 19:46:13 +08:00
@nthin0 很棒,采纳!
hantsy
2020-06-15 20:17:35 +08:00
也可以用数组 payment[] 封装结果 。
Vimax
2020-06-16 09:31:28 +08:00
@hantsy 谢谢,另类思路。追加采纳!
kennylam777
2020-06-20 18:54:52 +08:00
exchange +1 , getForEntity 對 Map/List 封裝就是個坑
siweipancc
2020-06-21 23:18:06 +08:00
:D 一直用 exchange,没发现这个问题,受教了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/681783

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX