jackson Webflux webclient和泛型类型

2skhul33  于 7个月前  发布在  其他
关注(0)|答案(3)|浏览(71)

我正在尝试构建一个将使用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 ParameterizedTypeReference<List<T>> (){}
                .block()
        catch(Exception e){}
}

}
问题是T在编译时被Object替换,整个过程返回的是LinkedHashMap的List而不是T的List。我尝试了很多方法,但没有运气。有线索吗?

w1jd8yoj

w1jd8yoj1#

我遇到了同样的问题,为了工作,我添加了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;
    }
}

并调用该函数,

ParameterizedTypeReference<List<MyClass>> typeReference = new ParameterizedTypeReference<List<MyClass>>(){};
List<MyClass> strings = getList(relativeUrl, typeReference);
a64a0gku

a64a0gku2#

如果你正在使用Kotlin,关键是使用reified来保留调用字段上泛型类型的类类型。
代码如下:

inline fun <reified T> getMonoResult(uriParam: String): T? = client
    .get()
    .uri(uriParam)
    .retrieve()
    .bodyToMono(T::class.java)
    .block(Duration.ofSeconds(1))

inline fun <reified T> getFluxResult(uriParam: String): MutableList<T>? = client
    .get()
    .uri(uriParam)
    .retrieve()
    .bodyToFlux(T::class.java)
    .collectList()
    .block(Duration.ofSeconds(1))
xhv8bpkk

xhv8bpkk3#

创建一个类(比如CollectionT),并将T的List作为属性添加到其中。然后你可以很容易地把它转换成Mono,在上面,.map(x -> x.getList())将返回T的列表的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());

    }
}

相关问题