ILoggable

A place to keep my thoughts on programming

March 28, 2007 java , , , , ,

Simple Java XML Serialization

Last time I used Java, JAXB was just being released. At least at the time, it was all about Schema definition and code generation. I loved the concept of serializing straight into XML and back, but code generation always is a bit of a nasty beast, imho. Plus, adding custom code to your class was also annoying. You basically had to extend your generated class to add anything custom to it.

When I started working with .NET, I was pleasantly surprised by their Attribute driven approach. Now the code and the XML definition was in one place and no post processing was required.

Back in Java land, I thought that with Java 5.0’s addition of Annotations, maybe the meta-data code-markup method had been picked up as well. Sure enough there is JAXB 2.0 Reflection. However, if all I want to do is some config files and maybe some data serialization without the full Web Services juggernaut, that seems like a heavy handed way of doing it.

A little further digging brought me to Simple. One tiny jar and you are ready to define, serialize and deserialize your classes. Woot. Sure, my .NET bias is showing, but I really like this approach so much better than starting at the XSD/DTD and generating code. And creating code that let’s you move objects from one side to the other is dead simple:

java

@Root(name="example")
public class Example {

   @Element(name="message")
   private String text;

   @Attribute(name="id")
   private int index;

   public Example() {
      super();
   }  

   public Example(String text, int index) {
      this.text = text;
      this.index = index;
   }

   public String getMessage() {
      return text;
   }

   public int getId() {
      return index;
   }
}

C#

[XmlRoot("example")]
public class Example
{

  private string text;
  private int index;

  public Example()
  {
  }

  public Example(string text, int index)
  {
    this.text = text;
    this.index = index;
  }

  [XmlElement("message")]
  public String Message
  {
    get { return text; }
    set { text = value; }
  }

  [XmlAttribute("id")]
  public int Id
  {
    get { return index; }
    set { index = value; }
  }
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<example id="123">
  <message>Example message</message>
</example>

The main difference is that the Simple approach doesn’t require there to be a public setter on the data, which is actually kind of strange. How does deserialization set the field? Does it use reflection Regardless, two pieces of code, looking quite similar, allowing you to serialize a class from C# to Java and back without a lot of work.

Leave a comment