Serialize Object to String in Java

In Java, we can serialize an object to String in different ways such as converting to byte[] and thenBase64 encoded string, XML or JSON. Learn with examples.

In Java, we can serialize an object to String in different ways and each method has its importance and usecase. Serialized strings are much easier to send (and debug) over the network, rather than byte arrays.

Out of several approaches, we are listing down the most common 3 approaches:

MechanismDiscussion
Serialize object to Byte[] and then encode byte[] to String– The Java object must implement the Serializable interface.
– No external dependency is required.
Serialize object to XML or JSON. Optionally, encode the XML or JSON.– It is optional to implement the Serializable interface.
– External dependency (Jackson or Gson) is needed.
– Base64 encoding/decoding is optional.

1. Serialize Object to Base64 Encoded String

In the default serialization mechanism in Java, we can serialize an Object to Byte[] if the Object implements the Serializable interface. Accomplishing serialization/deserialization takes place via the java.io.ObjectOutputStream and java.io.ObjectInputStream classes and writeObject()/readObject() methods.

In the following example, we have created the utility methods for the serialization and deserialization process:

public class SerializationUtils {

  public static String objectToString(Serializable obj) throws IOException {

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream ois = new ObjectOutputStream(baos)) {

      ois.writeObject(obj);
      return Base64.getEncoder().encodeToString(baos.toByteArray());
    }
  }

  public static Object stringToObject(String obj) throws IOException, ClassNotFoundException {

    byte[] data = Base64.getDecoder().decode(obj);
    try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
      return ois.readObject();
    }
  }
}

We can use the utility method objectToString() to convert the object to Base46 encoded string and the method stringToObject() to convert the base64 encoded string to a Java object as follows:

Person person = new Person(1, "Lokesh");

String encodedString = SerializationUtils.objectToString(person);
System.out.println(encodedString);

Person deserializedPerson = (Person) SerializationUtils.stringToObject(encodedString);
System.out.println(deserializedPerson);

The program output:

rO0ABXNyAENjb20uaG93dG9kb2luamF2YS5jb3JlLnNlcmlh....
Person[id=1, name=Lokesh]

Please note that the encoded string can be quite long because it contains several meta-information about the serialized object.

If we are interested in small strings (due to memory constraints), we can serialize the object into JSON or XML, first.

2. Serialize Object to JSON or XML

Another good way to serialize an object to String is to convert it to JSON or XML representation. One great advantage of this approach is that the Java class does not need to implement the Serializable interface. This is specially useful if the class is part of legacy source code and a 3rd-party library and we cannot modify the source code.

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(person);
System.out.println(json);

String deserializedPerson = mapper.readValue(json, Person.class);
System.out.println(deserializedPerson);

The program output:

{"id":1,"name":"Lokesh"}
Person[id=1, name=Lokesh]

For converting to the XML representation, use XmlMapper class instead of ObjectMapper. Everything else remains the same.

XmlMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(person);
System.out.println(xml);

String deserializedPerson = xmlMapper.readValue(xml, Person.class);
System.out.println(deserializedPerson);

The program output:

<Person><id>1</id><name>Lokesh</name></Person>
Person[id=1, name=Lokesh]

Irrespective of JSON or XML strings, if we require to have a Base64 encoded string, we can still apply the encode and decode methods on these strings. The generated encoded strings will be much smaller also, because it does not have the object’s meta-data information as well.

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(person);
String base64EncodedString = Base64.getEncoder().encodeToString(json.getBytes());
System.out.println(base64EncodedString);

String decodedJson = new String(Base64.getDecoder().decode(base64EncodedString));
deserializedPerson = mapper.readValue(decodedJson, Person.class);
System.out.println(deserializedPerson);

The program output:

eyJpZCI6MSwibmFtZSI6Ikxva2VzaCJ9
Person[id=1, name=Lokesh]

3. Summary

In this quick Java tutorial, we learned to convert a Java object to string representation, first by converting the object to byte[] and then its XML/JSON representation. We also learned to serialize and deserialize the strings to/from Base64 encoded values.

Happy Learning !!

Source Code on Github

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.