Thoughts on Web Services, part 5: To serialize or not to serialize
Most SOAP stacks offer some sort of XML serialization. Using this type of serialization, you can transform the parameters of your class to SOAP messages, and back again. This seems very handy: within certain limits, you do not need to change your class to SOAPify it! Useful, yes, but harmless?,
No. As it turns out, things are not so simple when you look up close. Why not?
First, let’s define our concepts a bit more. What is Serialization? I would define serialization as:
The reversible process of encoding a data structure as a sequence of bytes.
The standard Java and C# forms of serialization certainly conform to this definition, as do proprietary frameworks such as Hessian and Burlap. Does XML serialization? I’m a afraid not. Firstly, you cannot serialize any object into XSD-valid XML, and if you can serialize it, you cannot simply de-serialize it and expect the same object back.
The Alpine folks have excellently described why not. I will briefly cite the most important issues here:
- The language of XML Schema is much richer than the object model of Java,
- Not all XML names can be turned into Java identifiers,
xsd:enumerationdeclarations cannot be nicely mapped into Java types (even since Java 5),- Some Java types are by nature explicitly unportable.
- XML is a hierarchical data structure, and can only describe trees or lists of data, while Java classes almost invariably refer to other objects, often creating cyclic graphs of references.
- Each node in an XML message can have a separate namespace, which cannot be expressed in Java.
Read the article if you want the details.
In the end, the Alpine authors rather not talk about XML Serialization, but rather Object-XML Mapping (O/X Mapping). With this, they want to relate it to with Object-Relational Mappings, because it is at least as difficult.
However, I do not wish to go as far as to banish O/X mappings altogether, as the Alpine authors do. As with O/R mapping, a good O/X mapping can certainly be extremely useful, if properly configured. So, a good SOAP stack should facilitate in this configuration, and offer something like Spring’s templates to easily convert XML to objects and vice-versa. You do not expect Hibernate to automatically marshall your objects into SQL, why would you expect it when marshaling to XML?