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 编组?


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01