I'm using the FasterXML Jackson implementation to convert POJO's to XML output with the xml-databing package. I'm trying to achieve this output:
<MyRequest>
<MySubRequest>4</MySubRequest>
<MySubRequest>5</MySubRequest>
</MyRequest>
My classes:
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;
}
}
And:
@JacksonXmlRootElement
public class MyRequest {
private Collection<MySubRequest> MySubRequest;
public Collection<MySubRequest> getRequests() {
return MySubRequest;
}
public void setRequests(Collection<MySubRequest> requests) {
this.MySubRequest = requests;
}
}
I'm testing it with:
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);
But the output is:
<MyRequest xmlns="">
<requests>
<requests>12</requests>
<requests>34</requests>
</requests>
</MyRequest>
Another thing I'd like to know is how to force the output to be case-sensitive i.e. uppercase variable names.
You can use JacksonXmlElementWrapper
annotation to ignore the wrapper. Just use it like :
@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;
}
}
Here I have used JacksonXmlProperty
annotation to use element name as "MySubRequest" in xml.