我有以下Jax-RS端点:

@XmlRootElement(name = "foobar")
public class Foobar {}

@GET
@Produces(MediaType.APPLICATION_XML)
public Object getFoobars() {
    return new GenericEntity<List<FooBar>>(service.getFooBars());
}


使用Jersey 1.x,它曾经返回:

<foobars>
  <foobar>...</foobar>
  <foobar>...</foobar>
</foobars>


现在,我使用RestEasy,它将返回:

<collection>
  <foobar>...</foobar>
  <foobar>...</foobar>
</collection>


如何在Jax-RS中控制返回的GenericEntity<List<X>>的根名(使用Rest-Easy)?

请注意,我还返回Json格式,并且需要保持API向后兼容(例如,根元素是Json中的数组,应保持不变)

最佳答案

在深入研究RestEasy源代码之后,自己找到了解决方案。您只需将@Wrapped(element="___")批注添加到方法中:

import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;

@GET
@Produces(MediaType.APPLICATION_XML)
@Wrapped(element = "foobars")
public Object getFoobars() {
    return new GenericEntity<List<FooBar>>(service.getFooBars());
}


对于XML正确工作,对于JSON正确忽略。

09-10 02:53
查看更多