Note: Jackson does not use Java standard object serialization
Important Classes
ObjectInputStream
convert stream of bytes to object
method: Object readObject()
ObjectOutputStream
convert object to stream of bytes
method: void writeObject(Object o)
static fields belong to a class (as opposed to an object) and are not serialized
transient fields are not serialized
When a class implements the Serializable interface, all its sub-classes are serializable as well (since inheritance will make the subclass Serializable)
Conversely, when an field has a reference to another object, these objects must implement Serializable, or else a NotSerializableException will be thrown while performing serialization
If one of the fields is an array of objects, then all of these objects must implement Serializable as well, or else a NotSerializableException will be thrown while performing serialization
Person person = new Person();person.setAge(20);person.setName("Joe");// SerializationFileOutputStream fileOutputStream = new FileOutputStream("yourfile.txt");ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);objectOutputStream.writeObject(person);objectOutputStream.flush();objectOutputStream.close();// DeserializationFileInputStream fileInputStream = new FileInputStream("yourfile.txt");ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);Person p2 = (Person) objectInputStream.readObject();objectInputStream.close(); // AssertionsassertTrue(p2.getAge() == person.getAge());assertTrue(p2.getName().equals(person.getName()));
Custom Serialization
Use cases:
When you want to encrypt important fields of a class
When you want to use a more compressed serialization.
Java gives us two methods that we can use to customize the serialization process
void writeObject(ObjectOutputStream)
void readObject(ObjectInputStream)
None of these methods are inherited, overridden or overloaded
When the serialized data is deserialized, serialVersionUID is matched
If not matched InvalidClassException is thrown
If you don’t specify a serialVersionUID field in your Serializable classes, the Java compiler will specify one for you by doing expensive calculation which is highly sensitive to class details that may vary depending on compiler implementations
This may cause unnecessary InvalidClassException
class MyClass implements Serializable { private static final long serialVersionUID = 1L; // version 1.0}
transient (write a practical java example)
The transient keyword tells the Java standard serialization mechanism to ignore the field for the purposes of serialization
It is should but not must, since using custom serialization you can still serialize and not respect transient