[英]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. 我正在使用jersey-client v2.3.1编写一个rest客户端 ,需要使用包含一组 widget节点的根节点来解组xml响应。 Like something resembling the following ...
喜欢类似下面的东西......
<widgets>
<widget />
...
<widget />
</widgets>
Currently I have a Widget model ... 目前我有一个Widget模型......
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? 我的问题是,请问是否可以很好地解组,而无需使用jersey-client / jaxb创建包装类?
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
jaxb注释来检索集合...
@XmlRootElement
public class Widget {
...
}
And then modifying the client call to use the GenericType
class. 然后修改客户端调用以使用
GenericType
类。 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>>(){});
From JAXB point: 从JAXB点:
You can create XMLStreamReader and just skip first tag while unmarshalling. 您可以创建XMLStreamReader,只需在解组时跳过第一个标记。
XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream("widgets.xml"));
xmlStreamReader.nextTag(); // <widgets>
xmlStreamReader.nextTag(); // first <widget>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.