Webflux webclient 和泛型类型

lio*_*121 10 java spring jackson spring-webflux

我正在尝试构建一个将使用 REST api 的通用类。api 根据 url 返回对象列表。

我已经建立了一个通用类

public class RestConsumer<T> {
    WebClient client;

    public RestConsumer(){
        //Initialize client
    }

    public List<T> getList(String relativeUrl){
        try{
            return client
                .get()
                .uri(relativeUrl)
                .retrieve()
                .bodyToMono(new ParameterizeTypeReference<List<T>> (){}
                .block()
        catch(Exception e){}
}
Run Code Online (Sandbox Code Playgroud)

}

问题是 T 在编译时被 Object 替换,整个过程返回 LinkedHashMap 列表而不是 T 列表。我尝试了很多解决方法,但没有运气。有什么建议?

小智 20

我遇到了同样的问题,为了工作,我添加了 ParameterizedTypeReference 作为该函数的参数。

public <T> List<T> getList(String relativeUrl, 
                           ParameterizedTypeReference<List<T>> typeReference){
    try{
        return client
            .get()
            .uri(relativeUrl)
            .retrieve()
            .bodyToMono(typeReference)
            .block();
    } catch(Exception e){
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

并调用该函数

ParameterizedTypeReference<List<MyClass>> typeReference = new ParameterizedTypeReference<List<MyClass>>(){};
List<MyClass> strings = getList(relativeUrl, typeReference);
Run Code Online (Sandbox Code Playgroud)


Ash*_*ish -1

创建一个类(例如 CollectionT)并将 T 的 List 添加为其中的属性。然后,您可以轻松地将其转换为 Mono,其中 .map(x -> x.getList()) 将返回 T 的 List 的 Mono。它还通过避免 .block() 使您的代码看起来更加非阻塞

代码如下:->

public class CollectionT {

   private List<T> data;

   //getters
   public List<T> getData(){
    return data;
   }

   //setters
     ...
}

public class RestConsumer<T> {
    WebClient client = WebClient.create();

    public RestConsumer(){
        //Initialize client
    }

        public List<T> getList(String relativeUrl){

                return client
                    .get()
                    .uri(relativeUrl)
                    .retrieve()
                    .bodyToMono(CollectionT.class)
                    .map(x -> x.getData());

    }
}
Run Code Online (Sandbox Code Playgroud)