Question

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?

Was it helpful?

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>>(){});

OTHER TIPS

From JAXB point:

You can create XMLStreamReader and just skip first tag while unmarshalling.

 XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
 XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream("widgets.xml"));
 xmlStreamReader.nextTag(); // <widgets>
 xmlStreamReader.nextTag(); // first <widget>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top