ab11
ab11

Reputation: 20090

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?

Upvotes: 2

Views: 1235

Answers (2)

DwB
DwB

Reputation: 38300

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.

Upvotes: 3

Andreas
Andreas

Reputation: 159086

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

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

Upvotes: 1

Related Questions