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

yeg*_*256 17 java xml jaxb

以下是用例:

@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"));
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,我正在做:

JAXBContext ctx = JAXBContext.newInstance(Books.class);
Marshaller msh = ctx.createMarshaller();
msh.marshal(new Books(), System.out);
Run Code Online (Sandbox Code Playgroud)

这就是我所看到的:

<?xml version="1.0"?>
<books/>
Run Code Online (Sandbox Code Playgroud)

我的书在哪里?:)

Tom*_*ros 16

要编组的元素必须是公共的,或者具有XMLElement anotation.ArrayList类和您的类Books与这些规则中的任何一个都不匹配.您必须定义一个方法来提供Book值,并对其进行分析.

在您的代码上,只更改您的Books类添加"自我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;
  }
}
Run Code Online (Sandbox Code Playgroud)

当你运行你的编组代码时,你会得到:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<books><book><title>The Sign of the Four</title></book></books>
Run Code Online (Sandbox Code Playgroud)

(为了清晰起见,我添加了换行符)