如何使用 JAXB 编组/解组具有私有字段的 Java 对象

2022-01-19 00:00:00 xml marshalling java jaxb unmarshalling

我知道 JAXB API 的基础知识,但我一直在尝试做一些事情,我不确定它是否真的可行.详情如下:

I know the basics of the JAXB API, but I am stuck with something I am trying to do, and I am not sure whether it is actually possible. Details are as follows:

我有一个名为 Book 的类,其中包含 2 个字符串类型的 public 实例变量:

I have a class called Book with 2 public instance variables of type String:

@XmlRootElement(name="book")
public class Book
{
    public String title;
    public String author;

    public Book() {
    }
}

我有另一个名为 Bookshop 的类,其中有 1 个 ArrayList 类型的 public 实例变量:

I have a another class called Bookshop with 1 public instance variable of type ArrayList:

@XmlRootElement(name="bookshop")
public class Bookshop
{
    @XmlElementWrapper(name="book_list")
    @XmlElement(name="book")
    public ArrayList<Book> bookList;

    public Bookshop() {
        this.bookList = new ArrayList<>();
    }
}

注意:包声明和导入被删除以节省空间.

Note: package declaration and imports are removed in order to save space.

这两个类有效,我得到的输出 XML 类似于:

These two classes work and the output XML I get is something like:

<bookshop>
    <book_list>
        <book>
            <title>Book 1</title>
            <author>Author 1</author>
        </book>
        <book>
            <title>Book 2</title>
            <author>Author 2</author>
        </book>
    </book_list>
</bookshop>

据我所知,实例变量需要声明为 public 才能使其类可序列化.或者,可以将实例变量声明为私有,但在这种情况下需要访问器和修改器.

As far as I know, instance variables need to be declared public in order for its class to be serialisable. Or, instance variables can be declared private, but accessors and mutators are needed in that case.

我不喜欢公开实例变量;我喜欢使用访问器和修改器.即使这样,我也希望我的一些字段是只读的,即没有增变器.但是 JAXB 似乎对您想要编组/解组的每个字段都需要访问器和修改器.我想知道有没有办法解决这个问题?

I don't like declaring instance variables public; I like using accessors and mutators. Even then, I want some of my fields to be read-only, i.e., no mutator. But JAXB seems to require both accessors and mutators for each field you want to marshal/unmarshal. I was wondering if there is any way around this?

推荐答案

在任何情况下你都应该保持你的字段私有.您有 2 个选项绑定到字段

You should keep your fields private in any case. You have 2 options binding to fields

1) 使用 XmlElement 或 XmlAttribute 注释来注释您的字段

1) annotate your fields with XmlElement or XmlAttribute annotation

@XmlRootElement(name="book")
public class Book {
    @XmlElement
    private String title;
    ...

2) 使用 @XmlAccessorType(XmlAccessType.FIELD) 注释您的类

2) annotate your class with @XmlAccessorType(XmlAccessType.FIELD)

    @XmlRootElement(name="book")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Book {
         private String title;
         ...

相关文章