RESTEasy 返回的集合中的根元素名称

Root element name in collections returned by RESTEasy(RESTEasy 返回的集合中的根元素名称)

本文介绍了RESTEasy 返回的集合中的根元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JBoss AS 6 中通过 RestEasy 使用 JAX-RS.当我的 JAX-RS 资源返回项目集合(例如通过列表)时,RESTEasy 总是使用名称 collection 作为根元素.

I'm using JAX-RS via RestEasy in JBoss AS 6. When my JAX-RS resource returns a collection of items (e.g. via a List), RESTEasy always uses the name collection as the root element.

例如

<collection>    
   <item>
     <description>computer</description>
     <price>2500</price>
   </item>

   <item>
     <description>tv</description>
     <price>1500</price>
   </item>
</collection>

此 XML 由例如:

@Produces("application/xml")
@Path("xml")
@RequestScoped
public class MyResource {

    @GET
    @Path("myitems")
    public List<Item> getMyItems() {
        return ...
    }
}

可以看出,RESTEasy 创建的根标签始终是<collection>.

As can be seen the root tag that has been created by RESTEasy is always <collection>.

另一方面,Jersey 总是创建一个名称,该名称是列表中包含的元素的复数形式:

Jersey on the other hand always creates a name that is the plural form of the element contained in the list:

<items>    
   <item>
     <description>computer</description>
     <price>2500</price>
   </item>

   <item>
     <description>tv</description>
     <price>1500</price>
   </item>
</items>

我知道可以创建一个包装器类型并返回它而不是 List,但这是一个相当复杂的解决方法,并且使代码更加复杂.

I know it's possible to create a wrapper type and return that instead of a List, but that's a rather elaborate workaround and makes the code more complicated.

是否可以轻松地为集合指定根标签的名称?

Is it possible to easily specify what the name of the root tag is for collections?

推荐答案

貌似是RTFM的一个案例:RestEasy 文档 - JAXB 对象的数组和集合

Appeared to be a case of RTFM: RestEasy docs - Arrays and Collections of JAXB Objects

所以,如果我们想输出这个 XML

So, if we wanted to output this XML

<foo:list xmlns:foo="http://foo.org">
    <customer><name>bill</name></customer>
    <customer><name>monica</name></customer>
</foo:list>

我们会使用@Wrapped注解如下:

We would use the @Wrapped annotation as follows:

@GET
@Path("list")
@Produces("application/xml")
@Wrapped(element="list", namespace="http://foo.org", prefix="foo")
public List<Customer> getCustomerSet() { ... }

因此可以通过 @Wrapped 注释来实现.这是一个 RESTEasy 特定的,但现在就可以了.

It's thus possible via the @Wrapped annotation. It's a RESTEasy specific one, but this will do for now.

留下问题以防有人有更好的解决方案(仍在寻找一个全局拦截器 orso 让 RESTEasy 做 Jersey 做的事情).

Leaving the question open in case someone has an even better solution (still looking for a global interceptor orso that lets RESTEasy do what Jersey does).

这篇关于RESTEasy 返回的集合中的根元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:RESTEasy 返回的集合中的根元素名称

基础教程推荐