我使用FasterXML Jackson实现使用xml-databing包将POJO转换为XML输出。我试图实现这个输出:
<MyRequest>
<MySubRequest>4</MySubRequest>
<MySubRequest>5</MySubRequest>
</MyRequest>
我的课程:
public class MySubRequest {
@JacksonXmlText
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public MySubRequest(String id) {
super();
this.id = id;
}
}
和
@JacksonXmlRootElement
public class MyRequest {
private Collection<MySubRequest> MySubRequest;
public Collection<MySubRequest> getRequests() {
return MySubRequest;
}
public void setRequests(Collection<MySubRequest> requests) {
this.MySubRequest = requests;
}
}
我正在测试它:
ObjectMapper mapper = new XmlMapper();
MyRequest entity = new MyRequest();
Collection<MySubRequest> myIds = new ArrayList<>();
myIds.add(new MySubRequest("12"));
myIds.add(new MySubRequest("34"));
entity.setRequests(myIds);
mapper.writeValue(System.out, entity);
但输出是:
<MyRequest xmlns="">
<requests>
<requests>12</requests>
<requests>34</requests>
</requests>
</MyRequest>
我想知道的另一件事是如何强制输出区分大小写,即大写变量名。
答案 0 :(得分:1)
您可以使用JacksonXmlElementWrapper
注释来忽略包装器。只需使用它:
@JacksonXmlRootElement
class MyRequest {
private Collection<MySubRequest> mySubRequest;
public Collection<MySubRequest> getRequests() {
return mySubRequest;
}
@JacksonXmlProperty(localName = "MySubRequest")
@JacksonXmlElementWrapper(useWrapping = false)
public void setRequests(Collection<MySubRequest> requests) {
this.mySubRequest = requests;
}
}
这里我使用JacksonXmlProperty
注释将元素名称用作&#34; MySubRequest&#34;在xml。