Serialization and Deserialization in Java

Serialization is the name given to converting the state of an object to a byte stream so it can be sent over a network or written to a file and reverted into a copy of that object. The operation to covert the byte stream back to an object is called deserialization.

We can call writeObject() method ObjectOutputStream for serializing the object, where for deserializing we can call readObject() method of ObjectInputStream class.

Java provides Serializable API encapsulated under java.io package for serializing and deserializing objects followings are included,

  • Java.io.serializable
  • Java.io.Externalizable
  • ObjectInputStream
  • ObjectOutputStream
Java.io.Serializable interface

It is a marker interface, it is a unique interface in java without any field and method. It is used to inform the compiler that the class is implementing. It consists of some unique behaviour and meaning.

Example
		import java.io.Serializable;  
		public class Employee implements Serializable{  
		 int id;  
		 String name;
		 int salary;
		 public Student(int id, String name) {  
		  this.id = id;  
		  this.name = name;
		  this.salary = salary;
		 }  
		}  
	

In the above example, Employee class implements Serializable interface. Now its objects can be converted into the stream.

ObjectOutputStream class

ObjectOutputStream class is used to write object states to the file. It provides various methods to perform serialization. An object that implements java.io.Serializable interface can be written to streams.

ObjectOutputStream class serializes an object using the writeObject() method and sending it to the output stream.

public final void writeObject(object x) throws IOException
ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

In ObjectInputStream class, the readObject() method references object out of stream and deserialize it.

		public final Object readObject() throws 
		IOException,ClassNotFoundException
	
Example of Serializing an Object in Java

In this example, we have a class that implements Serializable interface to make its object serialized.

		import java.io.*;
		class Employeeinfo implements Serializable
		{
		    String name;
		    int rid;
		    static String contact;
		    Employeeinfo(String n, int r, String c)
		    {
		    this.name = n;
		    this.rid = r;
		    this.contact = c;
		    }
		}
		class Demo
		{
		    public static void main(String[] args)
		    {
		        try
		        {
		            Employeeinfo si = new Employeeinfo("Rohit", 1221, "9595000000");
		            FileOutputStream fos = new 
		FileOutputStream("employee.txt");
		            ObjectOutputStream oos = new ObjectOutputStream(fos);
		            oos.writeObject(si);
		            oos.flush();
		            oos.close();
		        }
		        catch (Exception e)
		        {
		            System.out.println(e);
		        }
		    }
		}
	

The object of Employeeinfo class is serialized using writeObject() method and written to employee.txt file.

Example of Deserialization of Object in Java
		import java.io.*;

		class Employeeinfo implements Serializable
		{
		    String name;
		    int empid;
		    static String contact;
		    Employeeinfo(String n, int e, String c)
		    {
		    this.name = n;
		    this.empid = e;
		    this.contact = c;
		    }
		}

		class Demo
		{
		    public static void main(String[] args)
		    {
		        Employeeinfo ei=null ;
		        try
		        {
		            FileInputStream fis = new 
		FileInputStream("/filepath/employee.txt");
		            ObjectInputStream ois = new ObjectInputStream(fis);
		            ei = (Employeeinfo)ois.readObject();
		        }
		        catch (Exception e)
		        {
		            e.printStackTrace(); }
		            System.out.println(ei.name);
		            System.out.println(ei.eid);
		            System.out.println(ei.contact);
		        }
		}
	
Output

Rohit

1221

null

In the above Output, Contact field is null because it is marked as static and we know that static field does not get serialized.

Java Transient keyword

When we don’t want to serialize any data member of a class, then it is marked as transient.

Example
		class Employeeinfo implements Serializable 
		{
		    String name;
		    transient int eid;
		    static String contact;
		}
	

In the above example, eid will not be serialized because it is transient,static.

XML Serialization

Java serialization does not have to result in cryptic files, objects can be serialized to readable formats. One of the most used serialization formats is XML and JDK provides classes to convert objects to XML and from XML back to the initial object. Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations, making it easy for Java developers to incorporate XML data and processing functions in Java applications. The operation to serialize an object to XML is named marshalling. The procedure to deserialize an object from XML is called unmarshalling. For a class to be serializable to XML, it has to be decorated with JAXB-specific annotations.

  • @XmlRootElement(name = “…”) is a top-level annotation placed at the class level to tell JAXB that the class name becomes an XML element at serialization time different name is needed for the XML element, it can be specified via the name attribute.
  • @XmlElement(name = “..”) is a method or field level annotation that tells JAXB that the field or method name becomes an XML element at serialization time; if a different name is needed for the XML element, it can be specified via the name attribute.
  • @XmlAttribute(name = “..”) is a method or field level annotation that tells JAXB that the field or method name becomes an XML attribute at serialization time; if a different name is needed for the XML attribute, it can be specified via the name attribute.
Java Architecture for XML Binding (JAXB)

Java Architecture for XML Binding (JAXB) was removed from JDK 11, so you must add external dependencies if you want to use it., you must add external dependencies. Here we use, it is also more than a little unstable, class com.sun.xml.internal.bind.v2.ContextFactory is part of the jaxb-impl library, which cannot be found on any public repository at the moment, at least not a version that was compiled with Java 11. The following is the code to make the Singer class serializable with JAXB.

		import javax.xml.bind.annotation.XmlAttribute;
		import javax.xml.bind.annotation.XmlElement;
		import javax.xml.bind.annotation.XmlRootElement;
		import java.io.Serializable;
		import java.time.LocalDate;
		import java.util.Objects;
		@XmlRootElement(name = “author”)
		public class Author implements Serializable {
		private static final long serialVersionUID = 42L;
		private String name;
		private Double rating;
		private LocalDate birthDate;
		public Author() {
		/* required for deserialization */
		}
		public Author(String name, Double rating, LocalDate birthDate) {
		this.name = name;
		this.rating = rating;
		this.birthDate = birthDate;
		}
		@XmlAttribute(name = “name”)
		public String getName() {
		return name;
		}
		@XmlAttribute(name = “rating”)
		public Double getRating() {
		return rating;
		}
		@XmlElement(name = “birthdate”)
		public LocalDate getBirthDate() {
		return birthDate;
		}
		...
		}
	

Notice the location where the annotations were placed. Based on the placement of the annotation in the code when the john object is serialized, the following is what you find in the matt.xml file.

		< ?xml version="1.0" encoding="utf-8"?>
		< singer name="Matt prior" rating="5.0">
		< birthdate>1977-10-16T00:00:00Z
		
	
JSON Serialization

JSON(JavaScript Object Notation) is a lightweight data-interchange format. It is readable for humans and is easy for machines to parse and generate. JSON is the favourite format for data being used in JavaScript applications, for REST-based application and is the internal format used by quite a few NoSQL databases. So, it is only appropriate that we show you how to serialize Java objects using this format. The advantage of serializing Java objects to JSON is that there is more than one library providing classes to do so, which means at least one of them is stable with Java 9+ versions.

The most preferred library for JSON serialization is the Jackson library. It can convert Java objects to JSON objects and back again without much code being written. Unfortunately, no version compatible with Java 9+ had been released yet, so for this section, a less advanced library compatible with Java 9+ will be used.

JSON format is a collection of key-pair values. The values can be arrays, or collections of key-pairs themselves. Converting Java objects to JSON objects using the JSON library (yes, it’s named exactly like that) is easy. We create a JSONObject and populate it with the Author object’s field names and values, and then we convert the JSONObject to String and eventually write it to a file. In the following code sample, we skipped the writing to file part, and we transform the String back into a copy of the initial Author object.

Copyright 1999- Ducat Creative, All rights reserved.