泽西岛客户端Xml集合解组

泽西岛客户端Xml集合解组

本文介绍了泽西岛客户端Xml集合解组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jersey-client v2.3.1 编写一个静态客户端,并且需要解组xml响应根节点包含小部件节点的集合.类似于以下内容...

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>

目前我有一个Widget模型...

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)

我的问题是,无需使用jersey-client/jaxb创建包装器类,就可以很好地解组请求吗?

My question is, can the request be unmarshalled nicely without having to create a wrapper class using jersey-client / jaxb?

推荐答案

以下两个参考文献将我引向解决方案...

The following two references led me to a solution ...

  • getEntity with GenericType
  • Jersey REST Client

没有包装类,可以使用应用于模型的@XmlRootElement jaxb批注来检索集合...

Without a wrapper class the collection can be retrieved with the @XmlRootElement jaxb annotation applied to the model ...

@XmlRootElement
public class Widget {
    ...
}

,然后修改客户端调用以使用GenericType类.要检索数组,可以调用...

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>>(){});

这篇关于泽西岛客户端Xml集合解组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:58