Search code examples
javaserializationxml-serialization

Which is the best alternative for Java Serialization?


I'm currently working on a project which needs to persist any kind of object (of which implementation we don't have any control) so these objects could be recovered afterwards.

We can't implement an ORM because we can't restrict the users of our library at development time.

Our first alternative was to serialize it with the Java default serialization but we had a lot of trouble recovering the objects when the users started to pass different versions of the same object (attributes changed types, names, ...).

We have tried with the XMLEncoder class (transforms an object into a XML), but we have found that there is a lack of functionality (doesn't support Enums for example).

Finally, we also tried JAXB but this impose our users to annotate their classes.

Any good alternative?


Solution

  • The easiest thing for you to do is still to use serialization, IMO, but put more thought into the serialized form of the classes (which you really ought to do anyway). For instance:

    1. Explicitly define the SerialUID.
    2. Define your own serialized form where appropriate.

    The serialized form is part of the class' API and careful thought should be put into its design.

    I won't go into a lot of details, since pretty much everything I have said comes from Effective Java. I'll instead, refer you to it, specifically the chapters about Serialization. It warns you about all the problems you're running into, and provides proper solutions to the problem:

    http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683


    With that said, if you're still considering a non-serialization approach, here are a couple:

    XML marshalling

    As many has pointed out is an option, but I think you'll still run into the same problems with backward compatibility. However, with XML marshalling, you'll hopefully catch these right away, since some frameworks may do some checks for you during initialization.

    Conversion to/from YAML

    This is an idea I have been toying with, but I really liked the YAML format (at least as a custom toString() format). But really, the only difference for you is that you'd be marshalling to YAML instead of XML. The only benefit is that that YAML is slightly more human readable than XML. The same restrictions apply.