Sunday, September 11, 2016

How-To serialize and deserialize Java objects to and from XML

Serialization is a powerful feature included in the Java framework. It allows for transporting and storing objects with great ease and flexibility. One drawback however is that the objects are serialized into a binary format and thus are hard to read or alter. That's where XML serialization comes in.

There are many XML serialization libraries available but many do not support popular Java classes out-of-the-box. One exception however, is XMLSerializer4j. It can serialize collections and most frequently used classes without requiring you to write your own serialization logic.

Serializing any object to an XML file is easy:
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.serialize(myObject, "MySerializedObject.xml");

Deserialize the XML back to an object like this:
XMLSerializer xmlSerializer = new XMLSerializer("MySerializedObject.xml");
Object myObject = xmlSerializer.deserialize();

By default the output will be stripped of unnecessary whitespace and line-breaks to save space. If however a human readable output is desired with line-breaks and indentation do this:
xmlSerializer.setTransformer(XMLSerializer.HUMAN_READABLE_TRANSFORMER);

Check out the documentation at the project's webpage for further explanation.

No comments:

Post a Comment