为什么Jersey / JAX-RS客户端无法处理泛型? [英] Why is Jersey/JAX-RS client unable to handle generics?
问题描述
我有一个Jersery / JAX-RS客户端,它打击了一个RESTful API(JSON),它应该返回一个我的POJO列表:
I have a Jersery/JAX-RS client that hits a RESTful API (JSON) that is supposed to return a list of my POJOs:
// Hits: GET localhost:8080/myapp/fizz/widget/{widget_id}
@Override
public List<Widget> getWidgetsByUser(Long id) {
return webResource.path("fizz").path("widget").path(id.toString()).get(List.class);
}
另外还有一个驱动程序用以测试客户端:
And a driver to test the client with:
public class Driver {
public static void main(String[] args) {
Driver d = new Driver();
d.run();
}
public void run() {
MyAppService myService = getSomehow();
List<Widget> widgets = myService.getWidgetResource().getWidgetsByUser(2L);
for(Widget widget : widgets) {
System.out.println("\t...and it found Widget #" + widget.getCaseId());
}
}
}
当我运行这个时,我get:
When I run this, I get:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.me.myapp.Widget
<stack trace omitted for brevity>
从for循环抛出异常:
The exception is being thrown from the for-loop:
for(Widget widget : widgets) {
这告诉我客户端有点工作,但我没有正确配置它。
Which tells me the client is sort of working, but that I don't have it configured correctly.
所以Jersey要么尝试返回纯JSON,要么不是试图将其映射回Widgets列表,或者我错误地调用了 get(Class<>)
方法。任何想法?
So either Jersey is trying to return pure JSON and isn't attempting to map it back to a list of Widgets, or I am invoking the get(Class<?>)
method incorrectly. Any ideas?
推荐答案
Pavel Horal的评论是正确的。如果没有已知的类型,Jackson(底层的deserilaizer)将映射到 LinkedHashMap
,所以它会返回 List< LinkedHashMap>
The comment by Pavel Horal is correct. Without a known type, Jackson (the underlying deserilaizer) will map to LinkedHashMap
, so it will return List<LinkedHashMap>
修正:
对于泛型类型,我们应该使用其他的 get()
方法,它需要一个 GenericType
参数。所以我们应该做一些像
For generic types, we should use the other get()
method, which takes a GenericType
argument. So we should do something like
...get(new GenericType<List<Widget>>(){});
这篇关于为什么Jersey / JAX-RS客户端无法处理泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!