简体   繁体   中英

How to serialize a list with Jackson without the list name?

I'm using this code:

XmlMapper objectMapper = new XmlMapper();
    objectMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    String xml = objectMapper.writeValueAsString(report);

To serialize this class:

class Report {

   List<Item> items;
}

The list of items is in an element called "items":

<Report>
<items>
<item>
</item>
<item>
...

I would like it to serialize without the "items" element:

<Report>
<item>
</item>
<item>
...

Any suggestions how I can do this with jackson?

This is just a slight variation on the @Andreas answer.

@JacksonXmlElementWrapper(localName = "ignoredName", useWrapping = false)
@JacksonXmlProperty(localName = "item")
private List<Item> itemList;

Use the @JacksonXmlElementWrapper annotation to identify that it is a list of stuff and you don't want a wrapper element. Use the @JacksonXmlProperty annotation to identify the element name.

This will cause a repetition of <item> xml elements in your output; one per entry in the itemList variable.

Add the @JacksonXmlElementWrapper annotation, specifying that you don't want a wrapper:

@JacksonXmlElementWrapper(useWrapping = false)
List<Item> items;

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