Jersey Client Xml Collection Unmarshalling

2019-08-08 19:02发布

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?

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-08 19:28

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>>(){});
查看更多
The star\"
3楼-- · 2019-08-08 19:43

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>
查看更多
登录 后发表回答