Skip to main content

Use XStream to serialize Java objects into XML

Perform object persistence, configuration, and data transport easily with XStream

Rajiv Bangalore (rajiv.bangalore@in.ibm.com), Senior Staff Software Engineer, IBM India Private Ltd.
Photo of Rajiv Bangalore
Rajiv Bangalore is a Senior Staff Software Engineer with IBM India. He has been involved in various Java Platform, Enterprise Edition (Java EE) development projects in his career spanning seven years. Contact him at rajiv.bangalore@in.ibm.com.

Summary:  XML serialization has a myriad of uses, including object persistence and data transport. However, some XML-serialization technologies can be complex to implement. XStream is a lightweight and easy-to-use open source Java™ library for serializing Java objects to XML and back again. Learn how to set up XStream, and discover how to use it to serialize and deserialize objects as well as to read configuration properties from an XML configuration file.

Date:  23 Jul 2008 (Published 08 Apr 2008)
Level:  Intermediate
Activity:  16941 views

Revisions on July 23, 2008: Under Serializing objects, added the Using Aliases sidebar.

Using XStream, you can serialize most Java objects without any mapping. Object names become element names in the XML produced, and the strings within classes form the element content of the XML. The classes that you serialize with XStream don't need to implement the Serializable interface. XStream is a serialization tool and not a data binding tool, which means that it doesn't perform class generation from an XML or XML Schema Definition (XSD) file.

Three features distinguish XStream from any other serializing tool:

  1. XStream doesn't care about the visibility of the fields of the class being serialized/deserialized.
  2. No getter and setter methods are required for the fields of the class to be serialized/deserialized.
  3. The class being serialized/deserialized is not required to have a default constructor.

You can directly serialize and deserialize any third-party class using XStream without making any changes to the class.

Setting up the development environment

Follow these steps to download and install XStream (see Resources for download links):

  1. Download Eclipse from the Eclipse Web site. To install, unpack it to any folder of your choice, which I'll refer to as eclipse_home in this article. This article assumes Eclipse version 3.3.
  2. Download the latest stable version of XStream from the XStream Web site. To install, unpack it to any folder of your choice, which I'll refer to as xstream_home. This article assumes XStream version 1.2.2.
  3. Download the Java Platform, Standard Edition (J2SE) software development kit (SDK) from the Sun Web site. Install it in any folder of your choice, which I'll refer to as java_home. This article assumes version 1.5.0_05.

Creating a Java project

To create a Java project, go to File > New > Project, then follow these steps:

  1. Go to Java > Java Project > Next (see Figure 1).

    Figure 1. Beginning a new Java project
    Beginning a new Java project

  2. Fill in the project name and click Next (see Figure 2).

    Figure 2. Filling in the project name
    Filling in the project name

  3. Click Finish to complete the task (see Figure 3).

    Figure 3. Finalizing the setup
    Finalizing the setup

Figure 4 shows the result of creating a Java project.


Figure 4. A new Java project
A new Java project

Adding XStream support

Follow these steps to add the XStream libraries to the project you just created:

  1. With the project selected in Project Explorer in Eclipse, go to the Project menu and choose Properties (see Figure 5).

    Figure 5. Adding XStream libraries
    Adding XStream libraries

  2. Click Add External JARs, and select xstream-1.2.2.jar from the xstream_home/lib folder.
  3. Click OK to complete the task (see Figure 6).

    Figure 6. Finalizing XStream support
    Finalizing XStream support

Figure 7 shows the result of adding XStream support to the project.


Figure 7. The added libraries
The added libraries

Serializing objects

Using Aliases

Element names in the generated XML contain the fully qualified class name. For example, <com.samples.Writer>. If you need only the class name (without the package name) as the XML element name, you have to use XStream Aliases. Please refer to the Alias Tutorial site.

This simple example, which demonstrates how you can serialize/deserialize objects using XStream, features two classes: Writer and Reader. The Writer class uses the XStream API to serialize an object of type Employee into XML and store it in a file in the file system (see Listing 1).


Listing 1. Writer.java
package com.samples;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.thoughtworks.xstream.*;

public class Writer {

    public static void main(String[] args) {
        Employee e = new Employee();

        //Set the properties using the setter methods
        //Note: This can also be done with a constructor.
        //Since we want to show that XStream can serialize
        //even without a constructor, this approach is used.
        e.setName("Jack");
        e.setDesignation("Manager");
        e.setDepartment("Finance");

        //Serialize the object
        XStream xs = new XStream();

        //Write to a file in the file system
        try {
            FileOutputStream fs = new FileOutputStream("c:/temp/employeedata.txt");
            xs.toXML(e, fs);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }
}

The Reader class reads this file, deserializes the XML, and gets the data into a Java object (see Listing 2).


Listing 2. Reader.java
package com.samples;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Reader {

    public static void main(String[] args) {
        XStream xs = new XStream(new DomDriver());
        Employee e = new Employee();

        try {
            FileInputStream fis = new FileInputStream("c:/temp/employeedata.txt");
            xs.fromXML(fis, e);

            //print the data from the object that has been read
            System.out.println(e.toString());

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

    }
}

Listing 3 shows the structure of the Employee object.


Listing 3. Employee.java

package com.samples;

public class Employee {
    private String name;
    private String designation;
    private String department;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(String designation) {
        this.designation = designation;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    @Override
    public String toString() {
        return "Name : "+this.name+
        "\nDesignation : "+this.designation+
        "\nDepartment : "+this.department;
    }
}


Reading a configuration file

Reading a complex XML file

This configuration example demonstrates reading a simple XML file. For reading a complex XML file, you might have to write a custom converter. A tutorial for writing converters is available at the XStream "Converter Tutorial" site (see Resources).

Most applications depend on a number of properties. These properties can be the name of a data source to connect to or the location of a log file. A configuration file is the best place to store this data, because it ensures that you can change these properties without recompiling the application, and it makes maintaining the application easier. This example scenario illustrates how you can use XStream in an application to read the configuration properties from an XML configuration file.

Typical XML data binding requires you to generate a Java object from an XML file. With XStream, there is no object-generation phase. You simply write a Java class and map the fields of the class to the elements of the XML that you wish to read. This example assumes the configuration file shown in Listing 4.


Listing 4. Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <datasource-name>IRIS</datasource-name>
    <ipaddress>9.124.74.85</ipaddress>
    <logfilename>DailyLogApplication.log</logfilename>
    <appender>console</appender>
</config>

Listing 5 shows the code for the ConfigReader class, which reads the configuration file and loads the properties into a Java object.


Listing 5. ConfigReader.java
package com.samples;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class ConfigReader {

    String datasourcename = null;
    String ipaddress = null;
    String logfilename = null;
    String appender = null;

    @Override
    public String toString() {
        // This method prints out the values stored in the member variables
        return "Datasource Name : "+datasourcename+
            " \nIP Address : "+ipaddress+
            " \nLogfilename : "+logfilename+
            " \nAppender : "+appender;
    }

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        XStream xs = new XStream(new DomDriver());

        FileInputStream fis = new FileInputStream("c:/temp/Config.xml");
        xs.aliasField("datasource-name", ConfigReader.class, "datasourcename");
        xs.alias("config", ConfigReader.class);
        ConfigReader r = (ConfigReader)xs.fromXML(fis);

        System.out.println(r.toString());
    }
}


Summary

To set up and develop an application with XStream is a simple matter of a few easy steps. Now that you know how to use XStream to serialize and deserialize Java objects and read configuration files, you can learn more about aliases, annotations, and converters at the XStream site (see Resources for tutorial links). Aliases and converters enable you to have complete control over the XML that is generated.



Download

DescriptionNameSizeDownload method
Java source code from this articlex-xstreamcode.zip3KB HTTP

Information about download methods


Resources

Learn

Get products and technologies

  • Eclipse: Download and install Eclipse from the Eclipse Web site.

  • Download XStream: From the XStream Web site, download this simple library to serialize objects to XML and back again.

  • IBM trial software: Build your next development project with trial software available for download directly from developerWorks.

Discuss

About the author

Photo of Rajiv Bangalore

Rajiv Bangalore is a Senior Staff Software Engineer with IBM India. He has been involved in various Java Platform, Enterprise Edition (Java EE) development projects in his career spanning seven years. Contact him at rajiv.bangalore@in.ibm.com.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Java technology, Open source
ArticleID=299097
ArticleTitle=Use XStream to serialize Java objects into XML
publish-date=07232008
author1-email=rajiv.bangalore@in.ibm.com
author1-email-cc=dwxed@us.ibm.com

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers