Welcome Guest!
Create Account | Login
Locator+ Code:

Search:
FTPOnline Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

Free Subscription to Java Pro

email article
printer friendly
get the code
more resources

Serialize Java Data Objects to XML
Save and Restore Java data objects to a compact, robust, and reusable XML form
by Charles D. Havener

June 2003 Issue


One of the least publicized new features of the Java Development Kit (JDK) 1.4 is the java.beans.XMLEncoder/XMLDecoder, which is built into the java.beans package. At a stroke this feature makes it possible to easily save and restore Java data objects, graphs of objects, and GUI state to a compact XML form that is so robust it continues to be usable even when the original class definitions change. There is nothing to download and install. It certainly saves JavaBeans, but don't be misled—it knows about collections, arrays, and many common nonbean data structures. You can also describe the data structure of your own or other third-party library classes to the encoder, using persistence delegates, and it can save those nonbean
objects, too.

ADVERTISEMENT

It doesn't take much to be a bean. A class just needs a public constructor that takes no arguments and get and set methods for each significant property such that a property named foo will have getFoo() and setFoo() methods. Technically, it must just support introspection, but that is usually achieved by using the get and set naming convention. Here is a simple Stuff bean for our experiments that has a String and an integer for properties:

package xmlpersist;

public class Stuff {
   private int k = 1;
   private String s = "hello";

   public Stuff() {}
   public int getK() {return k;}
   public String getS(){return s;}
   public void setK(int i) {k=i;}
   public void setS(String t){s=t;}
}

Having the persistence APIs handy will be useful to follow the examples and listings. They can be found in many places online (see Resources). The simple program to serialize the Stuff bean to XML and retrieve it is shown in Listing 1. The decoder just instantiates each object and invokes the standard bean public method calls setK and setS for the named properties k and s, passing them the arguments. Here is the emitted XML file:

<?xml version=
   "1.0" encoding="UTF-8"?> 
<java version=
   "1.4.1" class=
   "java.beans.XMLDecoder"> 
   <object class="xmlpersist.Stuff"> 
      <void property="k"> 
         <int>3</int> 
      </void> 
      <void property="s"> 
         <string>goodbye</string> 
      </void> 
   </object> 
</java>
Back to top













Java Pro | Visual Studio Magazine | Windows Server System Magazine
.NET Magazine | Enterprise Architect | XML & Web Services Magazine
VSLive! | Thunder Lizard Events | Discussions | Newsletters | FTP Home