Java Serialization and Deserialization: Concepts and Practices
The article explains serialization and deserialization fundamentals, highlights pitfalls such as ambiguous binary streams and platform‑dependent field sizes, then compares Java’s native ObjectOutputStream, JSON libraries, Hessian binary RPC, and Google’s Protobuf, guiding readers to select the appropriate format based on performance, payload size, and type‑safety needs.
The article starts by asking what serialization and deserialization mean, then explains common misconceptions such as treating data as a raw bit stream.
Two main problems are highlighted: (1) a long binary string lacks type and field boundaries, making deserialization ambiguous; (2) field sizes differ across platforms (e.g., int size on 32‑bit vs 64‑bit).
To address these, the author proposes using an intermediate format and reviews several Java serialization schemes.
JDK native serialization uses ObjectOutputStream/ObjectInputStream. A class must implement java.io.Serializable and optionally define a serialVersionUID to ensure compatibility after class changes.
class Item implements SerializableDuring interviews, serialVersionUID is often asked; it acts as a class “ID” used during deserialization.
JSON serialization is the most common in daily development, typically via libraries like JsonUtils. While easy to read, JSON loses type information and relies on reflection, which hurts performance and increases payload size.
Hessian is a binary RPC protocol offering higher efficiency than JSON. It requires the same Serializable marker. A Maven dependency example is provided:
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>x.x.x</version>
</dependency>Hessian is essentially a lightweight RPC service based on a binary protocol, similar to what Dubbo used before version 3.
Protobuf (Protocol Buffers) is a language‑agnostic, compact binary format developed by Google. An example .proto definition for a Person message is shown.
syntax = "proto3";
package tutorial;
message Person {
string name = 1;
int32 id = 2;
string email = 3;
optional string phone_number = 4;
enum Gender { MALE = 0; FEMALE = 1; OTHER = 2; }
Gender gender = 5;
}The article concludes that understanding these serialization mechanisms helps choose the right protocol based on performance, size, and type safety requirements.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.