Serialize Java Object to XML using XMLEncoder
Default java serialization converts the java objects into bytes to send over the network. But many times we will need a more cross-platform medium to send this information e.g. XML so that applications working on different technologies can also gain the advantage of this serialized information. In this example, we will learn to serialize the java objects into XML files and then de-serialize them back to the original java objects.
To demonstrate the usage, we have created a class UserSettings with 3 fields which we will serialize to XML and then de-serialize XML to java object.
public class UserSettings < private Integer fieldOne; private String fieldTwo; private boolean fieldThree; //constructors, setters, getters >
Let’s first see the example of XMLEncoder class which is used to serialize or encode a java object into an XML file.
private static void serializeToXML (UserSettings settings) throws IOException < FileOutputStream fos = new FileOutputStream("settings.xml"); XMLEncoder encoder = new XMLEncoder(fos); encoder.setExceptionListener(new ExceptionListener() < public void exceptionThrown(Exception e) < System.out.println("Exception! :"+e.toString()); >>); encoder.writeObject(settings); encoder.close(); fos.close(); >
XMLEncoder use reflection to find out what fields they contain, but instead of writing them in binary, they are written in XML. Objects that are to be encoded don’t need to be Serializable, but they do need to follow the Java Beans specification e.g.
- The object has a public empty (no-arg) constructor.
- The object has public getters and setters for each protected/private property.
Running the above code will generate the XML file with the below content:
Please note that if the default value of a property hasn’t changed in the object to be written, the XmlEncoder will not write it out. For example, in our case fieldThree is of type boolean which has default value as false – so it has been omitted from XML content. This allows the flexibility of changing what a default value is between versions of the class.
3. Deserialize XML to POJO
Now let’s see an example of XMLDecoder which has been used to deserialize the XML file back to a java object.
private static UserSettings deserializeFromXML() throws IOException
The XMLEncoder and XMLDecoder is much more forgiving than the serialization framework. When decoding, if a property changed its type, or if it was deleted/added/moved/renamed, the decoding will decode “as much as it can” while skipping the properties that it couldn’t decode.
Let’s see the whole example of using XMLEncoder and XMLDecoder .
import java.beans.ExceptionListener; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class XMLEncoderDecoderExample < public static void main(String[] args) throws IOException < UserSettings settings = new UserSettings(); settings.setFieldOne(10000); settings.setFieldTwo("HowToDoInJava.com"); settings.setFieldThree(false); //Before System.out.println(settings); serializeToXML ( settings ); UserSettings loadedSettings = deserializeFromXML(); //After System.out.println(loadedSettings); >private static void serializeToXML (UserSettings settings) throws IOException < FileOutputStream fos = new FileOutputStream("settings.xml"); XMLEncoder encoder = new XMLEncoder(fos); encoder.setExceptionListener(new ExceptionListener() < public void exceptionThrown(Exception e) < System.out.println("Exception! :"+e.toString()); >>); encoder.writeObject(settings); encoder.close(); fos.close(); > private static UserSettings deserializeFromXML() throws IOException < FileInputStream fis = new FileInputStream("settings.xml"); XMLDecoder decoder = new XMLDecoder(fis); UserSettings decodedSettings = (UserSettings) decoder.readObject(); decoder.close(); fis.close(); return decodedSettings; >>
UserSettings [fieldOne=10000, fieldTwo=HowToDoInJava.com, fieldThree=false] UserSettings [fieldOne=10000, fieldTwo=HowToDoInJava.com, fieldThree=false]
Drop me your questions in the comments section.
How to convert a Java object to XML using JAXB
Java Architecture for XML Binding (JAXB) is a popular choice for mapping Java objects to and from XML. It provides an easy-to-use programming interface for reading and writing Java objects to XML and vice versa.
In this guide, you’ll learn how to transform a Java object into an XML document. We’ll also look at an example of converting an XML document back to a Java object.
JAXB is a part of the Java Development Kit (JDK) since Java 1.6. So you don’t need any 3rd-party dependency to use JAXB in your project.
In JAXB terminology, Java object to XML conversion is referred to as marshalling. Marshalling is a process of converting a Java object to an XML document. JAXB provides the Marshall class to perform this conversion.
Before we discuss how marshaling works, let us first create two simple Java classes called Author and Book . These classes model a basic scenario where we have books, and each book has just one author. We start by creating the Author class to model the author: Author.java
public class Author private Long id; private String firstName; private String lastName; public Author() > public Author(Long id, String firstName, String lastName) this.id = id; this.firstName = firstName; this.lastName = lastName; > public Long getId() return id; > public void setId(Long id) this.id = id; > public String getFirstName() return firstName; > public void setFirstName(String firstName) this.firstName = firstName; > public String getLastName() return lastName; > public void setLastName(String lastName) this.lastName = lastName; > @Override public String toString() return "Author + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '>'; > >
The Author is a simple Java class with an ID, first and last names, with corresponding getting and setter methods. Next, we will create the Book class and annotate its fields with JAXB annotations to control how it should be marshalled to XML: Book.java
@XmlRootElement(name = "book") public class Book private Long id; private String title; private String isbn; private Author author; public Book() > public Book(Long id, String title, String isbn, Author author) this.id = id; this.title = title; this.isbn = isbn; this.author = author; > public Long getId() return id; > @XmlAttribute(name = "id") public void setId(Long id) this.id = id; > public String getTitle() return title; > @XmlElement(name = "title") public void setTitle(String title) this.title = title; > public String getIsbn() return isbn; > public void setIsbn(String isbn) this.isbn = isbn; > public Author getAuthor() return author; > @XmlElement(name = "author") public void setAuthor(Author author) this.author = author; > @Override public String toString() return "Book + "id=" + id + ", title='" + title + '\'' + ", isbn='" + isbn + '\'' + ", author=" + author + '>'; > >
- @XmlRootElement — This annotation is used at the top-level class to specify the root element of the XML document. The name attribute in the annotation is optional. If not specified, the class name is used as the root element name in the XML document.
- @XmlAttribute — This annotation is used to indicate the attribute of the root element.
- @XmlElement — This annotation is used on the fields of the class that will be the sub-elements of the root element.
That’s it. The Book class is now ready to be marshaled into an XML document. Let us start with a simple scenario where you want to convert a Java Object to an XML string.
To convert a Java object to an XML string, you first create an instance of JAXBContext . This is the entry point to JAXB API that provides several methods to marshal, unmarshal, and validate XML documents. Next, get the Marshall instance from JAXBContext . Afterward, use its marshal() method to marshall a Java object to XML. You can write the generated XML to a file, or a string, or print it on the console. Here is an example that converts a Book object to an XML string:
try // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Book.class); // create an instance of `Marshaller` Marshaller marshaller = context.createMarshaller(); // enable pretty-print XML output marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // write XML to `StringWriter` StringWriter sw = new StringWriter(); // create a `Book` object Book book = new Book(17L, "Head First Java", "ISBN-45565-45", new Author(5L, "Bert", "Bates")); // convert book object to XML marshaller.marshal(book, sw); // print the XML System.out.println(sw.toString()); > catch (JAXBException ex) ex.printStackTrace(); >
book id="17"> author> firstName>BertfirstName> id>5id> lastName>BateslastName> author> isbn>ISBN-45565-45isbn> title>Head First Javatitle> book>
Java object to an XML file conversion is similar to the above example. All you need to do is replace the StringWriter instance with an instance of File where you want to store the XML:
try // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Book.class); // create an instance of `Marshaller` Marshaller marshaller = context.createMarshaller(); // enable pretty-print XML output marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // create an XML file File file = new File("book.xml"); // create a `Book` object Book book = new Book(17L, "Head First Java", "ISBN-45565-45", new Author(5L, "Bert", "Bates")); // convert book object to XML file marshaller.marshal(book, file); > catch (JAXBException ex) ex.printStackTrace(); >
If you execute the above code snippet, you should see an XML file called book.xml generated with the same XML content as we have seen in the above example.
XML to Java object conversion or unmarshalling involves creating an instance of Unmarshaller from the JAXBContext and calling the unmarshal() method. This method accepts the XML file as an argument to unmarshal. The following example shows how you can convert the book.xml file, we just created, into an instance of Book :
try // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Book.class); // create an instance of `Unmarshaller` Unmarshaller unmarshaller = context.createUnmarshaller(); // XML file path File file = new File("book.xml"); // convert an XML file to a `Book` object Book book = (Book) unmarshaller.unmarshal(file); // print book object System.out.println(book); > catch (JAXBException ex) ex.printStackTrace(); >
Bookid=17, title='Head First Java', isbn='ISBN-45565-45', author=Authorid=5, firstName='Bert', lastName='Bates'>>
Sometimes, you want to marshal Java collection objects such as List , Map , or Set to an XML document and convert XML back to Java collection objects. For such a scenario, we need to create a special class named Books that holds a List of Book objects. Here is what it looks like: Books.java
@XmlRootElement(name = "books") public class Books private ListBook> books; public ListBook> getBooks() return books; > @XmlElement(name = "book") public void setBooks(ListBook> books) this.books = books; > public void add(Book book) if (this.books == null) this.books = new ArrayList>(); > this.books.add(book); > >
In the Books class above, the @XmlRootElement annotation indicates the root element of the XML as books . This class has a single List field with getter and setter methods. The add() method of this class accepts a Book object and adds it to the list. The following example demonstrates how you can convert a Java collection object into an XML document:
try // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Books.class); // create an instance of `Marshaller` Marshaller marshaller = context.createMarshaller(); // enable pretty-print XML output marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // create a `Books` object Books books = new Books(); // add books to list books.add(new Book(1L, "Head First Java", "ISBN-45565-45", new Author(1L, "Bert", "Bates"))); books.add(new Book(2L, "Thinking in Java", "ISBN-95855-3", new Author(2L, "Bruce", "Eckel"))); // convert `Books` object to XML file marshaller.marshal(books, new File("books.xml")); // print XML to console marshaller.marshal(books, System.out); > catch (JAXBException ex) ex.printStackTrace(); >
books> book id="1"> author> firstName>BertfirstName> id>1id> lastName>BateslastName> author> isbn>ISBN-45565-45isbn> title>Head First Javatitle> book> book id="2"> author> firstName>BrucefirstName> id>2id> lastName>EckellastName> author> isbn>ISBN-95855-3isbn> title>Thinking in Javatitle> book> books>
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.