Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 999
Kyle Avatar asked Jul 19 '10 20:07

Kyle


People also ask

How can we achieve serialization and deserialization in Java?

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class. We must have to implement the Serializable interface for serializing the object.

How do you customize serialization in Java?

Customized serialization can be implemented using the following two methods: private void writeObject(ObjectOutputStream oos) throws Exception: This method will be executed automatically by the jvm(also known as Callback Methods) at the time of serialization.

How many ways we can create serialization in Java?

Java Serialization Methods That's why there are four methods that we can provide in the class to change the serialization behavior.

Is there any other method to avoid serialization?

To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.


2 Answers

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

like image 175
Kathy Van Stone Avatar answered Sep 29 '22 00:09

Kathy Van Stone


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.

like image 42
mikera Avatar answered Sep 29 '22 00:09

mikera