DEV Community

Britt Codes
Britt Codes

Posted on

How to Serialize & De-Serialize Objects in Java

Below is an example detailing steps to take on serializing and de-serializing an object.

Why do you need to know about serialization? The process of serialization allows an object's state to be converted to bytes and transferred over a network or saved to a hard disk. While deserialization reconstructs the object from its bytes.

1. Create the class to be serialized and implement the Serializable interface.

NOTE: The NotSerializableException will be thrown if the Object to be serialized does not implement the java.io.Serializable interface.

import java.io.Serializable;

public class Student implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1729322620831679876L;
    private String name;
    private int grade;
    private int age;

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Student(String name, int grade, int age) {
        super();
        this.name = name;
        this.grade = grade;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getGrade() {
        return grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + grade;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (grade != other.grade)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", grade=" + grade + ", age=" + age + "]";
    }

}

Enter fullscreen mode Exit fullscreen mode

2. Use ObjectOutputStream class and writeObject(Object obj) method to write the objects to a file.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.LinkedList;
import java.util.List;

public class Write {

    public static void main(String[] args) {
        List<Student> registers = new LinkedList<>();
        registers.add(new Student("Harry Potter", 9, 14));
        registers.add(new Student("Hermoine Granger", 9, 14));
        registers.add(new Student("Ron Weasley", 9, 14));
        registers.add(new Student("Neville LongBottom", 9, 14));
        registers.add(new Student("Luna Lovegood", 10, 15));
        registers.add(new Student("Ginevra Weasley", 8, 13));
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Registry.ser"));
            oos.writeObject(registers);
            oos.close();
            System.out.println("Objects successfully written to registry list.");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Enter fullscreen mode Exit fullscreen mode

3. Use ObjectInputStream to deserialize the object and use the readObject() method to read the objects.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import java.util.List;

public class Read {

    public static void main(String[] args) {
        List<Student> list = new LinkedList<>();
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Registry.ser"));
            list = (List<Student>) ois.readObject();
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for(Student s:list) {
            System.out.println(s);
        }
    }

}

Enter fullscreen mode Exit fullscreen mode

Happy Coding! 😃

Discussion (0)