Serializing a named list unintuitive
See original GitHub issueMy use case is very simple, I have to create an XML document that has, among others, a list of “item” nodes with a parent “items” node. It could look like this:
<channel>
<items>
<item>...</item>
<item>...</item>
</items>
</chanell>
However, the naive approach of using a list/array cannot seem to produce this with any amount of configuration via annotations:
public class Channel
{
public final List<Item> items = new ArrayList<>();
}
public class Item
{
}
// Produces: <channel><items><items></items>...</items></channel>
Ultimately, the only way I was able to create the output conforming to the schema from above was to create a useless wrapper class, turn off wrapping, and name my list nonsensically:
public class Channel
{
public final Items items = new Items();
}
public class Items
{
@JacksonXmlElementWrapper(useWrapping=false)
public final List<Item> item = new ArrayList<>();
}
public class Item
{
}
// Produces: <channel><items><item></item>...</items></channel>
This does result in the correct output schema, but now I am forced to access my objects in a non-intuitive way. For instance, if I want to add an item to my list of items, I must call the following:
channel.items.item.add(new Item());
which looks like I am adding an Item to another Item, rather than the list of items.
What I expected to work but did not was the following:
public class Channel
{
// with wrapping enabled, the parent node should be "<items>"
public final List<Item> items = new ArrayList<>();
}
// Each Item instance should be rendered as "<item>"
@JacksonXmlRootElement(localName="item")
public class Item
{
}
This would allow me to access my data in a sane manner:
channel.items.add(new Item());
TL;DR - It seems to me that @JacksonXmlRootElement(localName="item")
does not work on any object in a collection/array, and instead the localName of the collection is used for the parent node (correct) AND each object in the collection/array (incorrect).
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
Have you tried this?
OK, I think I have found a solution:
Which gives me exactly what I wanted:
However I am not entirely sure if it is a bug that if I didn’t specify
@JacksonXmlElementWrapper(useWrapping = false)
I would end up with an output like this: