Why Jersey / JAX-RS client can't handle generics?

I have a Jersery / JAX-RS client that hits a RESTful API (JSON) that should 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());
        }
    }
}

      

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>

      

Exception thrown from for loop:

for(Widget widget : widgets) {

      

Which tells me that the client is working, but I configured it incorrectly.

So either Jersey is trying to return pure JSON rather than trying to translate it back into the Widgets list, or I'm calling the method get(Class<?>)

incorrectly. Any ideas?

+2


source to share


1 answer


Paul Choral's commentary is correct. Without a known type, Jackson (base deserilaizer) will map to LinkedHashMap

, so it will returnList<LinkedHashMap>

Fix:



For generic types, we have to use another method get()

that accepts GenericType

. Therefore, we have to do something like

...get(new GenericType<List<Widget>>(){});

      

+4


source







All Articles