Explain Codes LogoExplain Codes Logo

How to serialize an object into a string

java
serialization
deserialization
base64
Alex KataevbyAlex Kataev·Sep 11, 2024
TLDR

To serialize your Java object to a string, you'll employ ObjectOutputStream and ByteArrayOutputStream coupled with Base64 encoding. Here's the gist:

import java.io.*; import java.util.Base64; public class Serializer { public static String serialize(Serializable obj) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream objectStream = new ObjectOutputStream(byteStream); // Just like Harry Potter's magic spell 🧙‍♂️: "Serialize-us Stringify-us!" objectStream.writeObject(obj); return Base64.getEncoder().encodeToString(byteStream.toByteArray()); } }

Simply call Serializer.serialize(yourObject) to get a Base64 string. Don't forget to make sure your yourObject classes implements Serializable.

BLOB or CLOB? It's Not An Alien Movie.

BLOBs (Binary Large Objects) or CLOBs (Character Large Objects) can be used for storing the serialized object. The nature and size of your data dictates their use. Use BLOB for binary data, CLOB for textual data, choose wisely young padawan!

Encoding and Decoding - Escaping The Matrix

Encode your serialized data to Base64 for safe storage. To avoid Neo's issue with characters that aren't supported, this is your protocol:

public static Object deserialize(String base64String) throws IOException, ClassNotFoundException { byte[] data = Base64.getDecoder().decode(base64String); // Popping jelly beans out of the packet ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data)); return objectInputStream.readObject(); }

Database, Meet Java. Java, Meet Database.

You can courageously defy Von Neumann’s architecture and put serialized objects straight into the BLOB/CLOB fields in your database using JDBC:

PreparedStatement ps = connection.prepareStatement( "INSERT INTO your_table (blob_column) VALUES (?)"); // Insert the painting into the gallery, where 'gallery' is the database ps.setBlob(1, new SerialBlob(serialize(yourObject).getBytes(StandardCharsets.UTF_8))); ps.executeUpdate();

Remember to change blob_column and your_table to fit your own schema, unless of course you are really using those names, in which case 😳.

Time Travel – Dealing with Legacy

If you are using Java 7 or earlier, the java.util.Base64 class will treat you as a ghost. Use Apache Commons Codec or similar to regain corporeal form.

Dealing with the Timey-Wimey Stuff

Maintain serialVersionUID in your classes for backward compatibility. Java allows the serializing or, let's be straightforward, freezing of objects—a key part in the wibbly-wobbly timey-wimey stuff of software development.

Some Potentially Knightmare-ish Situations A.K.A Pitfalls

  • Security Risks: This isn't exactly a Horcrux from Harry Potter. Untrustworthy can lead to security risks, always validate input before deserialization.
  • Performance Quirks: Large objects? Complex graphs? You might feel the burn with memory and CPU usage.
  • Maintainability: Serialized objects in a database are like mildew, can become a headache if not managed properly. Strategy is key!