gpt4 book ai didi

java - 如何使用 Spring ClientResponse 使用 Map?

转载 作者:行者123 更新时间:2023-12-04 15:16:48 27 4
gpt4 key购买 nike

首先,我有一个像这样公开的 REST URL:

   @PostMapping("/check/existence")
@ResponseBody
public Map<String, MyObjectDto> checkExistence() {
//some code

然后,我有一个带有 Spring WebClient 的消费者,就像这样:

   ClientResponse response = webclient.post().uri....

我想做这样的事情:

   Map<String, MyObjectDto> responseDto = 
response.bodyToMono(Map.class).block();

但控制台返回给我

   java.util.LinkedHashMap cannot be cast to  org.mypackage.MyObjectDto

那么,我怎样才能使用像 Map<String, MyObjectDto> 这样类型的 map 呢? ?

最佳答案

来自documentation类(class) ParameterizedTypeReference<T>

The purpose of this class is to enable capturing and passing a generic Type. In order to capture the generic type and retain it at runtime, you need to create a subclass (ideally as anonymous inline class) as follows:

当您需要将某些东西序列化/反序列化为使用泛型的类型时(例如 Map 或 List)

你不能使用

response.bodyToMono(Map.class)

这样一来,spring 就不知道你想把什么类型实际放入 Map 中了。你要输入一个int吗?一个字符串?一个东西?它不知道。

因此您需要提供包含类型信息的内容。

bodyToMono(new ParameterizedTypeReference<Map<String, MyObjectDto>>() {})

ParameterizedTypeReference是一个匿名类,它将为您保存您的类型信息。因此,当我们将类传递给通用函数 bodyToMono 时,该类就像一个容器来保存您的类型信息,这样 spring 就可以查看该对象的内容并确定您想要使用的类型。

关于java - 如何使用 Spring ClientResponse 使用 Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64170975/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com