XML Serialization of Java Objects

Sometimes it is necessary to stream objects in a standard way like XML or JSON. There are different ways of doing so. Below I will take an example of XStream to illustrate how Java Objects can be serialized into XML.

is an open source, a very light weight and easy to use API to Serialize Java Objects into XML and back. Below is a simple example:

import com.mypack.Person;

//The object to serialize
Person p = new Person();
p.setAddress("Lahore, Pakistan");

//Serializing p
XStream xstream = new XStream(new PureJavaReflectionProvider(), new DomDriver());

The above code will serialize the object of type Person to the following XML. There are other toXML(..) methods available to write the XML to a Writer and OutputStream.

    <address>Lahore, Pakistan</address>

The above XML can be deserialized back to the Java object. The following fromXML(..) method is overloaded, see the API for more details.

import com.mypack.Person;

String xml = &quot;&lt;...&gt;&quot;; //The above xml

//Deserializing back to Person
XStream xstream = new XStream(new PureJavaReflectionProvider(), new DomDriver());
Person p = (Person) xstream.fromXML(xml);

Another approach is using JAXB, a Java-XML binding API. JAXB uses XML Schemas to generate Java classes; the objects of these generated artifacts can then be serialized to XML.

Leave a Reply