为什么我的 ArrayList 没有使用 JAXB 进行编组?

2022-09-02 21:51:40

下面是一个用例:

@XmlRootElement
public class Book {
  public String title;
  public Book(String t) {
    this.title = t;
  }
}
@XmlRootElement
@XmlSeeAlso({Book.class})
public class Books extends ArrayList<Book> {
  public Books() {
    this.add(new Book("The Sign of the Four"));
  }
}

然后,我正在做:

JAXBContext ctx = JAXBContext.newInstance(Books.class);
Marshaller msh = ctx.createMarshaller();
msh.marshal(new Books(), System.out);

这是我所看到的:

<?xml version="1.0"?>
<books/>

我的书在哪里?:)


答案 1

要封送处理的元素必须是公共的,或者具有 XMLElement 注释。ArrayList 类和您的类 Books 都不匹配这些规则中的任何一个。您必须定义一个提供 Book 值的方法,并对其进行注释。

在你的代码上,只更改你的 Books 类,添加一个“self getter”方法:

@XmlRootElement
@XmlSeeAlso({Book.class})
public class Books extends ArrayList<Book> {
  public Books() {
    this.add(new Book("The Sign of the Four"));
  }

  @XmlElement(name = "book")
  public List<Book> getBooks() {
    return this;
  }
}

当您运行编组代码时,您将获得:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<books><book><title>The Sign of the Four</title></book></books>

(为了清晰的摇晃,我添加了换行符)


答案 2

我不认为你可以轻易地按原样编组。请考虑使用另一个类来包装列表。以下工作原理:List

@XmlType
class Book {
    public String title;

    public Book() {
    }

    public Book(String t) {
        this.title = t;
    }
}

@XmlType
class Books extends ArrayList<Book> {
    public Books() {
        this.add(new Book("The Sign of the Four"));
    }
}

@XmlRootElement(name = "books")
class Wrapper {
    public Books book = new Books();
}

用法如下:

JAXBContext ctx = JAXBContext.newInstance(Wrapper.class);
Marshaller msh = ctx.createMarshaller();
msh.marshal(new Wrapper(), System.out);

它产生这样的结果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<books><book><title>The Sign of the Four</title></book></books>

推荐