使用Jersey将REST资源作为List 获取

我正在尝试在Jersey中编写一个generics函数,它可以用来通过REST获取相同类型的对象列表。 我基于此论坛中的信息: 链接

@Override public  List fetchResourceAsList(String url) { ClientConfig cc = new DefaultClientConfig(); Client c = Client.create(cc); if (userName!=null && password!=null) { c.addFilter(new HTTPBasicAuthFilter(userName, password)); } WebResource resource = c.resource(url); return resource.get(new GenericType<List>() {}); } 

但是这不起作用。 如果我尝试执行它,我会收到以下错误: SEVERE: A message body reader for Java class java.util.List, and Java type java.util.List, and MIME media type application/xml was not found

但是,如果我在没有模板化的情况下编写此函数(用实际的类名替换T),它就可以正常工作。 当然这种方式失去了它的意义。

有没有办法来解决这个问题?

我找到了解决方案https://java.net/projects/jersey/lists/users/archive/2011-08/message/37

 public  List getAll(final Class clazz) { ParameterizedType parameterizedGenericType = new ParameterizedType() { public Type[] getActualTypeArguments() { return new Type[] { clazz }; } public Type getRawType() { return List.class; } public Type getOwnerType() { return List.class; } }; GenericType> genericType = new GenericType>( parameterizedGenericType) { }; return service.path(Path.ROOT).path(clazz.getSimpleName()) .accept(MediaType.APPLICATION_XML).get(genericType); } 

请参阅GenericType类的jersey,这也可能对您有所帮助

Unmarshaller需要知道对象的类型,然后才能取消归还返回的内容。 由于generics信息在运行时不可用,因此您无法提出要求。 它不能解决它不知道任何事情的事情。

你能做的最好的是;

 public  List fetchResourceAsList(Class beanClass, String url) { ... if(beanCLass.equals(MyBean.class)){ return resource.get(new GenericType>() }else if(...){ ... }... } 

或者使用generics警告(我不确定这是否有效)

 public List fetchResourceAsList(String url) { ... return resource.get(new GenericType>() } 

扩展到user2323189,您可以使用Collection而不是List.class,这样您就可以序列化所有扩展Collection的类型。 我在我的基本客户端类中创建了一个简单的getter,可以简单地使用它来检索任何类型的Collection。 不是我的构造函数中提供的clazz变量,因此它不是提供的参数。 您可以将其转换为静态方法,并使用带有Class参数的签名GenericType>使其更通用。

 public GenericType> getParameterizedCollectionType() { ParameterizedType parameterizedGenericType = new ParameterizedType() { public Type[] getActualTypeArguments() { return new Type[] { clazz }; } public Type getRawType() { return Collection.class; } public Type getOwnerType() { return Collection.class; } }; return new GenericType>(parameterizedGenericType){}; }