News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

Serialise objects with XStream

Started by Kalyan, Nov 27, 2008, 04:28 PM

Previous topic - Next topic

Kalyan

Serialise objects with XStream

XML isn't the panacea that its evangelists claimed it would be, but it does have a place in IT and will be around for a long time.

Configuration files are popular (though not) glamorous uses of XML schemas. For the corporate programmer, XML config files aren't as accessible as they should be. Even though XML is just text, the overhead necessary to parse the XML is usually too high a price to pay for smaller applications. Well, now there's XStream.

XStream isn't a config file parser by trade. In the words of its creators, XStream is "a simple library to serialise objects to XML and back again". As soon as I saw it, I knew it solved at least one of my long-running problems. It's a perfect fit for parsing and writing small, simple XML files a la config files.

Here's a simple example to show how you could use XStream to read a configuration file for a fictitious application that needs to know a server's location.

The config file looks like this:


<authServer>
<port>1080</port>
  <server>localhost</server>
</authServer> 

The code for reading the XML and creating the AuthServer config object looks like this:


XStream xs = new XStream();

xs.alias("authServer", AuthServerConfig.class);

AuthServerConfig asc = (AuthServerConfig) xs.fromXML(xml);

The above code looks too good to be true, but it's not. XStream doesn't have any external dependencies; it doesn't require an XML parser; it doesn't need mapping files, and so on.

If you're looking for a simple way to get your objects out of XML or vice versa, it's worth your time to take a look at XStream and see if it's useful to you.

Here's an example of related code:


import java.util.Date;
import com.thoughtworks.xstream.XStream;

public class XStreamTip {
private static String xml =
"<authServer>"

+
"<port>1080</port>"
+
"<server>localhost</server>"

+
"</authServer>";



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

xs.alias("authServer",
AuthServerConfig.class);

AuthServerConfig
asc = (AuthServerConfig) xs.fromXML(xml);
System.out.println(asc);

System.out.println(xs.toXML(asc));

}
}

class AuthServerConfig {
private int port;

private String server;

public void setPort(int port) {
this.port =
port;
}

public int getPort() {

return
this.port;}

public void setServer(String server)
{

this.server =
server;
}

public String getServer() {

return
this.server;
}
}

source : builderau