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

标签 java xml jackson jackson-dataformat-xml

使用 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);

关于java - Jackson XML 列表元素匹配它们的根名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49325423/

相关文章:

java - 将两个表示为链表的数字相加

java - 将多个 JAXB 元素片段组合成一个根节点?

java - 有没有办法在运行时忽略 Jackson 字段而不使用 @JsonIgnore

json - 在Groovy中使用多个数组构建JSON

java.lang.ClassNotFoundException : com. fasterxml.jackson.annotation.JsonInclude$Value

java - 实现库中定义的接口(interface)

Java三元运算符和后缀/前缀运算

python - BeautifulSoup 结契约(Contract)名标签

Java:当抛出异常并使用异常映射器时,客户端会收到什么 REST 响应?

xml - 找不到类路径资源 [bean.xml] 中定义的名称为 'helloworld' 的 bean 的类 [com.springdemo]