Why my ArrayList is not marshalled with JAXB?(为什么我的 ArrayList 没有使用 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)
这篇关于为什么我的 ArrayList 没有使用 JAXB 编组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我的 ArrayList 没有使用 JAXB 编组?


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01