Serialization in Android – A Detailed Explanation
📘 What is Serialization?
Serialization is the process of converting an object into a format that can be stored or transmitted — like a file, bundle, or over the network. The opposite process, deserialization, is converting that format back into an object.
Think of serialization like converting a real-life object into a string or byte stream so it can be saved, transferred, or shared.
📱 Why is Serialization Used in Android?
In Android, serialization is used for several reasons:
🔍 Key Characteristics of Serialization:
📦 How Serialization Works (Conceptually)
Let’s say you have this data class:
data class User(val name: String, val age: Int)
When you serialize this:
{"name": "John", "age": 25}
🛠️ Types of Serialization in Android (Overview)
🧪 Detailed Explanation of Each Type
1. 🧱 Java Serialization (Serializable)
import java.io.Serializable
data class User(val name: String, val age: Int): Serializable
Used in:
intent.putExtra("user", user)
val user = intent.getSerializableExtra("user") as? User
🟥 Downside: Not optimized for Android (poor performance on large objects or lists).
Recommended by LinkedIn
2. ⚡ Android Parcelable
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class User(val name: String, val age: Int): Parcelable
Used in:
intent.putExtra("user", user)
val user = intent.getParcelableExtra<User>("user")
✅ Recommended for Android UI component communication
3. 🌐 JSON Serialization (Gson, Moshi, kotlinx.serialization)
Using Gson:
val gson = Gson()
val json = gson.toJson(User("Tom", 28)) // Serialization
val user = gson.fromJson(json, User::class.java) // Deserialization
Using kotlinx.serialization:
@Serializable
data class User(val name: String, val age: Int)
val json = Json.encodeToString(User("Tom", 28))
val user = Json.decodeFromString<User>(json)
✅ Great for:
🔄 Serialization vs Deserialization
📚 Real-World Example
Let’s say you're working on a chat app. You receive this JSON:
{"sender": "Alice", "message": "Hello!", "timestamp": 1615207200}
You can:
✅ Summary
Senior Android Engineer | 8 y.exp. | Follow for practical insights on Android, Clean Architecture, and Kotlin
2wNice breakdown! But you missed a few important points: - There’s a limitation on how large an Object you can pass between screens using a Bundle. - If you're actually passing an object as an argument during navigation, it's usually a sign of poor design. So, it's not the best example to use