杰克逊XML列表元素匹配其根名称

时间:2018-03-16 16:23:37

标签: java xml jackson jackson-dataformat-xml

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

例如,给定以下类

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>

1 个答案:

答案 0 :(得分:0)

我无法在杰克逊找到这样做的方法,但在JAXB中这几乎是微不足道的。

cumsum

解组:

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;
    }
}