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.

XStream
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.setName("Kamran");
p.setAddress("Lahore, Pakistan");

//Serializing p
XStream xstream = new XStream(new PureJavaReflectionProvider(), new DomDriver());
System.out.println(xstream.toXML(p));

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.

<com.mypack.Person>
    <name>Kamran</name>
    <address>Lahore, Pakistan</address>
</com.mypack.Person>

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