How to marshal / unmarshal private field Java objects using JAXB

I know the basics of the JAXB API, but I'm stuck in something I'm trying to do, and I'm not sure if this is really possible. Details:

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

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

I have another class called Bookshop with 1 public variable of an instance 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 declarations and imports are deleted to save space.

These two classes work, and the XML output is obtained as follows:

 <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 must be declared public so that its class can be serializable. Or instance variables can be declared private, but accessors and mutators are needed in this case.

I do not like to declare public instance variables; I like to use accessors and mutators. Even then, I want some of my fields to be read-only, i.e. No mutator. But JAXB apparently requires both accessors and mutators for each field that you want to marshal / untie. I was wondering if there was anything like that?

+6
source share
2 answers

In any case, you must keep your fields private. You have 2 options for field binding

1) annotate your fields using XmlElement or XmlAttribute annotation

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

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

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

JAXB is needed: - an open instance variable Or - A private instance variable with public mutators and accessories.

You will need mutators for sorting and accessors for unmarshalling

-3
source

Source: https://habr.com/ru/post/943723/


All Articles