我正在寻找一种方法,可以在通过Web服务发布时使用JAXB轻松更改对象列表的元素名称。这是一个例子:
假设我有一个想要序列化为XML的对象:
@XmlRootElement(name = "greeting")
public class TestClassForSo {
public String id;
public List<String> description;
}
我有一个Web服务,它将这些对象的列表发布为XML:
@GET
@Path("/so-test")
@Produces({AgiMediaType.APPLICATION_XML, AgiMediaType.APPLICATION_JSON})
@XmlElementWrapper(name = "wrapperName")
public List<TestClassForSo> getGreetings() {
List<TestClassForSo> greetingList = new ArrayList<>();
TestClassForSo greeting = new TestClassForSo();
String id = "hello-word";
List<String> greetings = new ArrayList<>(Arrays.asList("Hello World,
Bonjour le monde,
Hallo Welt,
Hola Mundo"));
greeting.id = id;
greeting.description = greetings;
greetingList.add(greeting);
return greetingList;
}
当我通过HTTP GET调用请求资源时,我得到以下结果:
<testClassForSoes>
<greeting>
<id>hello-word</id>
<description>Hello World, Bonjour le monde, Hallo Welt, Hola Mundo</description>
</greeting>
</testClassForSoes>
是否有一种简单的方法可以将列表的元素名称更改为greetings
,而不是将其放入包装器方法或编写自己的序列化机制等?
显然,由于命名惯例,我无法更改TestClassForSo
的名称。
作为一个附带问题,这个问题真的很重要,除了让人类更容易理解列表的元素名称是什么?
感谢您查看问题。任何帮助表示赞赏。我已经在网上查看了类似的问题,但似乎没有任何内容完全适合我的问题。
问候
答案 0 :(得分:1)
只有JAXB才能实现这一点,因为注释必须是 放在
ArrayList
班级上。解决方案是使用杰克逊
ObjectWriter
的方法:withRootName()
但是,我认为为此创建自己的包装类非常简单,因为Jersey不允许根名称自定义:
@XmlRootElement(name = "greetings")
public class RootClass {
@XmlElement(name = "greeting")
public List<TestClassForSo> greetingList;
}
并将方法的策略更改为以下内容,例如:
@GET
@Path("/so-test")
@Produces({AgiMediaType.APPLICATION_XML, AgiMediaType.APPLICATION_JSON})
public RootClass getGreetings() {
List<TestClassForSo> greetingList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
TestClassForSo testClassForSo = new TestClassForSo();
String id = "hello-word";
List<String> greetings = new ArrayList<>(Arrays.asList("Hello World " + i));
testClassForSo.id = id;
testClassForSo.description = greetings;
greetingList.add(testClassForSo);
}
RootClass r = new RootClass();
r.greetingList = greetingList;
return r;
}
然后,我们得到最终结果:
<greetings>
<greeting>
<id>hello-word</id>
<description>Hello World 0</description>
</greeting>
<greeting>
<id>hello-word</id>
<description>Hello World 1</description>
</greeting>
<greeting>
<id>hello-word</id>
<description>Hello World 2</description>
</greeting>
</greetings>