Serialization is used to convert an object’s state into a format that can be easily stored or transmitted, such as a string. In this article, we will see how to serialize an object into a string with Java’s built-in serialization mechanism.

Serializing an Object into a String:

To serialize an object into a string, you can use the ObjectOutputStream class along with a ByteArrayOutputStream. Following is the step-by-step process of how you can do it.

Let us first get started by importing the required classes.

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

Create a class to serialize

class Person implements Serializable {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Create an object and serialize it into a string

public class ObjectToStringSerialization {

    public static String serializeToString(Object object) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            oos.close();
            return bos.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        Person person = new Person("Alice", 30);
        String serializedString = serializeToString(person);
        System.out.println("Serialized String: " + serializedString);
    }
}

Explanation

In the above example, we define a Person class that implements the Serializable interface. This interface is a marker interface that indicates the class can be serialized.

The serializeToString() method takes an object and uses an ObjectOutputStream to serialize it into a ByteArrayOutputStream. The byte stream is then converted to a string using the toString() method of the byte array output stream.

In the main() method, we create a Person object, serialize it into a string using serializeToString(), and finally display the serialized string.

References:

https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html

https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html

Categorized in:

Tagged in: