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

2022-01-19 00:00:00 xml java 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"));
  }
}

那么,我在做:

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

这是我看到的:

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

我的书在哪里?:)

推荐答案

要编组的元素必须是公共的,或者具有 XMLElement 注释.ArrayList 类和您的类 Books 不符合任何这些规则.您必须定义一个方法来提供 Book 值并对其进行注释.

The elements to be marshalled must be public, or have the XMLElement anotation. The ArrayList class and your class Books do not match any of these rules. You have to define a method to offer the Book values, and anotate it.

在您的代码中,仅更改您的 Books 类,添加self getter"方法:

On your code, changing only your Books class adding a "self getter" method:

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

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

when you run your marshalling code you'll get:

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

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

(I added a line break for clarity's shake)

相关文章