我正在使用 jersey-client v2.3.1 编写一个休息客户端并且需要使用包含小部件节点集合的根节点来解码 xml 响应。像下面这样的东西......
<widgets>
<widget />
...
<widget />
</widgets>
目前我有一个 Widget 模型 ...
public class Widget {
...
}
但是我没有这个模型的包装器(至少现在还没有),但我想我可以创建一个允许对响应进行解码的包装器。它可能看起来像这样......
@XmlRootElement(name="widgets")
public class WidgetResponse {
@XmlElement(name="widget")
public Widget[] widgets;
}
在这种情况下,我的休息电话可能是......
ClientBuilder.newClient()
.target("http://host/api")
.path("resource")
.request(MediaType.APPLICATION_XML)
.get(WidgetsResponse.class)
我的问题是,是否可以很好地解码请求而不必使用 jersey-client/jaxb 创建包装器类?
最佳答案
以下两个引用使我找到了解决方案......
如果没有包装类,可以使用应用于模型的 @XmlRootElement
jaxb 注释来检索集合 ...
@XmlRootElement
public class Widget {
...
}
然后修改客户端调用以使用 GenericType
类。要检索数组,您可以调用 ...
Widget[] widgets = ClientBuilder.newClient()
.target("http://host/api")
.path("resource")
.request(MediaType.APPLICATION_XML)
.get(new GenericType<Widget[]>(){});
或者类似地检索您可以调用的列表......
List<Widget> widgets = ClientBuilder.newClient()
.target("http://host/api")
.path("resource")
.request(MediaType.APPLICATION_XML)
.get(new GenericType<List<Widget>>(){});
关于java - 泽西客户端 Xml 集合解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803681/