Sample

This is a very simple example that shows how cedarsoft Serialization works. This sample is based on Stax Mate.

The business object

We can serialize all kinds of business objects. cedarsoft Serialization just provides the structure while the specific code is hand written.

In this sample we serialize a simple money object with just one value:

public class Money {
  private int cents;

  public Money( int dollars, int cents ) {
    this.cents = dollars * 100 + cents;
  }

  public Money( int cents ) {
    this.cents = cents;
  }

The resulting XML

This is a sample XML that is created by a very simple serializer:

<?xml version="1.0" encoding="UTF-8"?>
<money xmlns=""http://www.cedarsoft.com/test/money/1.0.0">>1199</money>

The second line defines a namespace that contains the format version. If the XML format has to be changed, the version number is increased.

The design of cedarsoft Serialization offers a very easy way to handle the old formats, too.

The serialization class

For each business class there should be one serializer. So for our Money class we create the class MoneySerializer. The creation of this serializer and test stubs can be done using the generator.

public class MoneySerializer extends AbstractStaxMateSerializer<Money> {
  public MoneySerializer() {
    super( "money", "http://thecompany.com/test/money", new VersionRange( new Version( 1, 0, 0 ), new Version( 1, 0, 0 ) ) );
  }

  @Override
  public void serialize( SMOutputElement serializeTo, Money object, Version formatVersion ) throws IOException, XMLStreamException {
    assert isVersionWritable( formatVersion );
    serializeTo.addCharacters( String.valueOf( object.getCents() ) );
  }

  @Override
  public Money deserialize( XMLStreamReader deserializeFrom, Version formatVersion ) throws IOException, XMLStreamException {
    assert isVersionReadable( formatVersion );
    int cents = Integer.parseInt( getText( deserializeFrom ) );

    //We don't have to close the tag. The getText method does that for us
    return new Money( cents );
  }
}