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

查看:108
本文介绍了为什么我的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 anotation。 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天全站免登陆