问题
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?
回答1:
The following two references led me to a solution ...
- getEntity with GenericType
- Jersey REST Client
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>>(){});
回答2:
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>
来源:https://stackoverflow.com/questions/19803681/jersey-client-xml-collection-unmarshalling