When building enterprise-grade systems, moving data between services or persisting it efficiently is essential. This is where serialization and deserialization come into play.
πΉ What Is Serialization?
Serialization is the process of converting an in-memory object into a transferable format such as JSON, XML, or binary.
This allows us to send objects across the network, store them in databases, or log them in a readable format.
πΉ What Is Deserialization?
Deserialization is the reverse process: taking serialized data (like a JSON string) and transforming it back into an object instance in memory.
πΉ Objects vs JSON
- Object β Runtime entity in memory, created from a class.
- JSON β Text-based, language-independent format used to represent structured data.
Example:
// Java object
class User {
private String name;
private int age;
// Constructors, getters, setters, toString()
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
// Getters & Setters...
}
// JSON representation of the object
{
"name": "Alice",
"age": 30
}
πΉ Serialization with Jackson
Weβll use Jacksonβs ObjectMapper (a widely used JSON library in Java).
import com.fasterxml.jackson.databind.ObjectMapper;
public class SerializationDemo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
User user = new User("Alice", 30);
// Object β JSON (Serialization)
String json = mapper.writeValueAsString(user);
System.out.println("Serialized JSON: " + json);
}
}
Output:
Serialized JSON: {"name":"Alice","age":30}
πΉ Deserialization with Jackson
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeserializationDemo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"Alice\",\"age\":30}";
// JSON β Object (Deserialization)
User user = mapper.readValue(json, User.class);
System.out.println("Deserialized Object: " + user);
}
}
Output:
Deserialized Object: User{name='Alice', age=30}
πΉ Why JSON?
- β Human-readable and lightweight
- β Language-independent
- β Native support in REST APIs
- β Wide ecosystem of libraries (Jackson, Gson, Moshi, etc.)
πΉ Final Thoughts
Serialization and deserialization form the backbone of data exchange in modern distributed systems.
Understanding the difference between an object (in memory) and its JSON (text representation) helps developers design cleaner, scalable APIs and systems.
Top comments (0)