Jackson XML 列表元素匹配它们的根名称

Jackson XML List Elements Match Their Root Name

使用 Jackson 的 XmlMapper,有没有办法让对象列表的元素名称与 @JacksonXmlRootElement 中给出的 localName 相匹配?

例如,给出以下 类

interface Foo {}

@JacksonXmlRootElement(localName = "bar")
class Bar implements Foo {}

@JacksonXmlRootElement(localName = "baz")
class Baz implements Foo {}

@JacksonXmlRootElement(localName = "container")
class FooContainer {
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Foo> foos;

    FooContainer(List<Foo> foos) {
        this.foos = foos;
    }

    public List<Foo> getFoos() {
        return foos;
    }
}

使用 XmlMapper

FooContainer container = new FooContainer(Arrays.asList(new Bar(), new Baz()));
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValueAsString(container);

我们得到如下XML

<container>
  <foos/>
  <foos/>
</container>

有没有办法得到这个?

<container>
  <bar/>
  <baz/>
</container>

我还没有找到在 Jackson 中执行此操作的方法,但在 JAXB 中这几乎是微不足道的。

interface Foo {}

class Bar implements Foo {}

class Baz implements Foo {}

@XmlRootElement(name = "container")
@XmlAccessorType(XmlAccessType.FIELD)
class FooContainer {
    @XmlElements({
        @XmlElement(name = "bar", type = Bar.class),
        @XmlElement(name = "baz", type = Baz.class)
    })
    private List<Foo> foos;

    FooContainer() {}

    FooContainer(List<Foo> foos) {
        this.foos = foos;
    }

    public List<Foo> getFoos() {
        return foos;
    }
}

解组:

FooContainer container = new FooContainer(Arrays.asList(new Bar(), new Baz()));

JAXBContext jaxbContext = JAXBContext.newInstance(FooContainer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(container, System.out);