简体   繁体   中英

How to marshal/unmarshal Java objects with private fields using JAXB

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:

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() {
    }
}

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.

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>

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.

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, ie, 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?

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

1) annotate your fields with XmlElement or XmlAttribute annotation

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

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

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

JAXB will need either: - A public instance variable Or - A private instance variable with public mutators and accessors.

You will need mutators for marshalling and acessors for unmarshalling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM