Dropwizard 反序列化来自 JerseyClient 的通用列表序列化、列表、Dropwizard、JerseyClient

2023-09-06 15:22:51 作者:橙色女招待

I wanted to implement a generic class to use for caching results from a REST API in a local MongoDB-instance. For this to work, I need to deserialize a collection I get from JerseyClient:

Response response = this.source.request().get();
List<T> list = response.readEntity( new GenericType<List<T>>() {} );

// ... do stuff with the list

Let's say I'm using this piece of code in a context of T relating to a class Foo. The really weird thing is, after the readEntity call, list is not a List<Foo>, instead is a List<LinkedHashMap>. How is that even possible, when I've clearly declared the Generic T to be Foo?

RESTfulWebServiceswithDropwizard.pdf 其它文档类资源 CSDN下载

What do I have to do to get a proper List<T>, i.e. List<Foo> instead?

Note: If I remove the generic, and use

List<Foo> list = response.readEntity( new GenericType<List<Foo>>() {} );

directly instead, it works fine, but I really need that generic to be there!

解决方案

Java's most popular excuse for Generics: Type Erasure

If you can pass your class type as Class<T> clazz, then you can use this:

GenericType<List<T>> genericType = new GenericType<>(new ParameterizedType() {
  public Type[] getActualTypeArguments() {
    return new Type[]{clazz};
  }

  public Type getRawType() {
    return List.class;
  }

  public Type getOwnerType() {
    return null;
  }
});
response.readEntity(genericType);