Kyle
Kyle

Reputation: 22035

How can I have more flexible serialization and deserialization in Java?

If I serialize an object in Java, and then later add an extra field to the java class, I can't deserialize the object into the modified class.

Is there a serialization library or some way that I can have deserialization be less strict, like if there is an extra field added to the class then it just fills that with null upon deserialization of the old version of the class?

Upvotes: 5

Views: 1415

Answers (6)

user207421
user207421

Reputation: 310903

If I serialize an object in Java, and then later add an extra field to the java class, I can't deserialize the object into the modified class.

That's untrue for a start. You need to have a good look at the Versioning section of the Object Serialization specification before you go any further.

Upvotes: 0

Kathy Van Stone
Kathy Van Stone

Reputation: 26271

You need to keep a serialVersionUID on your class. Check out the section "Version Control" in this article by Sun.

Upvotes: 7

Jonathan Holloway
Jonathan Holloway

Reputation: 63672

There's a fair few serialization libraries, take a look at Simple though:

http://simple.sourceforge.net/

or as mentioned above Google Protocol Buffers.

http://code.google.com/apis/protocolbuffers/

Upvotes: 1

Dominik
Dominik

Reputation: 1252

Did you add a serialVersionUID? This must be present (and unchanged) if you want to serialize / deserialize different Versions of a class.

Furthermore you can add the following two methods to your class to define exactly the serialization process:

private void writeObject(java.io.ObjectOutputStream stream)
 throws IOException;
private void readObject(java.io.ObjectInputStream stream)
 throws IOException, ClassNotFoundException; 

The Javadoc of ObjectInputStream gives more detail on its usage.

Upvotes: 0

mikera
mikera

Reputation: 106351

You've got lots of potential options.

You could use a graph serialisation library to define and manage your format e.g. Google's protocol buffers or Kryo. I believe both of these have built-in support for versioning.

You can write your own custom serialisation code and handle the versions explicitly - e.g. serializing to a flexible format like XML. When reading the XML you can configure it to use default values if a particular field isn't specified.

Or you could design your class in a "flexible" way, e.g. have all the fields stored in a HashMap and indexed by Strings. Depending on what you are trying to do, this may be a convenient option.

Upvotes: 5

Will Hartung
Will Hartung

Reputation: 118641

Implement Externalizable and you can do whatever you want. The puts the onus of serial/deserialization completely upon the class being serialized.

Upvotes: 0

Related Questions