简体   繁体   中英

Jackson FasterXML POJO to XML list

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 ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM