Jersey Client Xml Collection Unmarshalling

一个人想着一个人 提交于 2020-01-05 09:34:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!