Serialize Object to String in Java: Base64 and JSON
Serialize object to String in Java with ObjectOutputStream and Base64 or with Jackson JSON, read it back, and avoid the deserialization security risk.
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Notice that for a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable or java.io.Externalizable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
Objects to be stored and retrieved frequently refer to other objects. Those other objects must be stored and retrieved at the same time to maintain the relationships between the objects. When an object is stored, all of the objects that are reachable from that object are stored as well.
Now browse below tutorials to gain more insights about java serialization.
Serialize object to String in Java with ObjectOutputStream and Base64 or with Jackson JSON, read it back, and avoid the deserialization security risk.
Java IO tutorial for Java 25 covering Path and Files, byte and character streams, NIO channels, how IO works in the OS, and every file task by topic.
Java custom serialization with private readObject() and writeObject(), defaultWriteObject(), validation after reading, readResolve() and records.
Use XMLEncoder and XMLDecoder to save Java objects as XML, handle errors with ExceptionListener, store records and avoid decoding untrusted XML.
Externalizable vs Serializable in Java with a runnable example, constructor rules, read order, real size numbers, versioning, records and security.
The serialVersionUID versions a Serializable class in Java. See the declaration rules, InvalidClassException, the computed default, serialver and records.
Java deep copy using in-memory serialization with a generic helper, shared references, transient fields, SerializationUtils, real cost and alternatives.
Java serialization explained with Serializable, serialVersionUID, transient fields, records, readObject, Externalizable and deserialization filters.
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.