Serialize Java Object to XML – XMLEncoder and XMLDecoder Example

Default java serialization convert the java objects into bytes to send over network. But many times you will need a more cross-platform medium to send this information e.g. XML so that application working on different technologies can also gain advantage of this serialized information. In this example, we will learn to serialize the java objects into XML file and then de-serialize back to original java objects.

To demonstrate the usage, I have create a class UserSettings with 3 fields which we will serialize to xml and then de-serialize xml to java object.

public class UserSettings {
	
	public UserSettings(){}
	
	private Integer fieldOne;
	private String fieldTwo;
	private boolean fieldThree;

	public Integer getFieldOne() {
		return fieldOne;
	}

	public void setFieldOne(Integer fieldOne) {
		this.fieldOne = fieldOne;
	}

	public String getFieldTwo() {
		return fieldTwo;
	}

	public void setFieldTwo(String fieldTwo) {
		this.fieldTwo = fieldTwo;
	}

	public boolean isFieldThree() {
		return fieldThree;
	}

	public void setFieldThree(boolean fieldThree) {
		this.fieldThree = fieldThree;
	}

	@Override
	public String toString() {
		return "UserSettings [fieldOne=" + fieldOne + ", fieldTwo=" + fieldTwo
				+ ", fieldThree=" + fieldThree + "]";
	}
}

Serialization with XMLEncoder from java object to XML file

Let’s first see the example of XMLEncoder class which is used to serialize or encode a java object into 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 these fields 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.

  1. The object has a public empty (no-arg) constructor.
  2. The object has public getters and setters for each protected/private property.

Running the above code will generate the XML file with 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 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.

De-serialization with XMLDecoder from XML to java object

Now let’s see example of XMLDecoder which has been used to deserialize the xml file back to 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.

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

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

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Serialize Java Object to XML – XMLEncoder and XMLDecoder Example”

  1. I want to encode only Json Object data with UTF-8.
    Suppose any special characters in my json data, they need to be encoded with UTF-8. Please help me.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.