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.

1. Setup

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
}

2. Serialize POJO to XML

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:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_92" class="java.beans.XMLDecoder">
  <object class="com.howtodoinjava.log4j2.examples.UserSettings">
    <void property="fieldOne">
      <int>10000</int>
    </void>
    <void property="fieldTwo">
      <string>HowToDoInJava.com</string>
    </void>
  </object>
</java>

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 {

	FileInputStream fis = new FileInputStream("settings.xml");
	XMLDecoder decoder = new XMLDecoder(fis);
	UserSettings decodedSettings = (UserSettings) decoder.readObject();
	decoder.close();
	fis.close();
	return decodedSettings;
}

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.

4. Complete Example

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;
    }
}

The program output:

UserSettings [fieldOne=10000, fieldTwo=HowToDoInJava.com, fieldThree=false]
UserSettings [fieldOne=10000, fieldTwo=HowToDoInJava.com, fieldThree=false]

Drop me your questions in the comments section.

Happy Learning !!

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.