为什么我的 ArrayList 没有使用 JAXB 编组? [英] Why my ArrayList is not marshalled with JAXB?

查看:24
本文介绍了为什么我的 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 编组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆