Search code examples
javaxmlrestjax-rsjersey-client

Jersey Client Xml Collection Unmarshalling


I'm writing a rest client using jersey-client v2.3.1 and need to unmarshal an xml response with a root node containing a collection of widget nodes. Like something resembling the following ...

<widgets>
    <widget />
    ...
    <widget />
</widgets>

Currently I have a Widget model ...

public class Widget {
    ...
}

However I do not have a wrapper for this model (at least not yet), but I presume I could create one that would allow the response to be unmarshalled. It'd probably look something like this ...

@XmlRootElement(name="widgets")
public class WidgetResponse {
    @XmlElement(name="widget")
    public Widget[] widgets;
}

In which case my rest call would likely be ...

ClientBuilder.newClient()
    .target("http://host/api")
    .path("resource")
    .request(MediaType.APPLICATION_XML)
    .get(WidgetsResponse.class)

My question is, can the request be unmarshalled nicely without having to create a wrapper class using jersey-client / jaxb?


Solution

  • The following two references led me to a solution ...

    Without a wrapper class the collection can be retrieved with the @XmlRootElement jaxb annotation applied to the model ...

    @XmlRootElement
    public class Widget {
        ...
    }
    

    And then modifying the client call to use the GenericType class. To retrieve an array you can call ...

    Widget[] widgets = ClientBuilder.newClient()
        .target("http://host/api")
        .path("resource")
        .request(MediaType.APPLICATION_XML)
        .get(new GenericType<Widget[]>(){});
    

    Or similarly to retrieve a list you can call ...

    List<Widget> widgets = ClientBuilder.newClient()
        .target("http://host/api")
        .path("resource")
        .request(MediaType.APPLICATION_XML)
        .get(new GenericType<List<Widget>>(){});