Sobes.tech
Junior

What is serialization?

sobes.tech AI

Answer from AI

Serialization is the process of converting an object into a byte sequence for storage or transmission. Deserialization is the reverse process: restoring the object from this sequence.

In Android, it is often used for:

  • Transferring data between Activity/Fragment via Intent (implementation of Parcelable).
  • Saving user interface state.
  • Storing data in SharedPreferences or files.
  • Transmitting data over the network (e.g., JSON, Protobuf).

Main mechanisms in Android:

  • Serializable: Standard Java interface. Easy to implement but slower and creates more garbage compared to Parcelable. Uses reflection.
  • Parcelable: Android-specific interface. Faster and more efficient for inter-process communication (IPC). Requires manual implementation of writeToParcel() and createFromParcel() methods.
  • JSON/XML: For data transfer over the network. Requires parsing libraries (e.g., GSON, Jackson, Moshi).

Example of using Parcelable:

@Parcelize
data class User(val id: Int, val name: String) : Parcelable

(using @Parcelize plugin for Kotlin)

Example of using Serializable:

public class Product implements Serializable {
    private int id;
    private String name;

    public Product(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // getters and setters
}

Choosing between Serializable and Parcelable depends on the task. For IPC, Parcelable is preferred. For saving objects to disk or transmitting over the network, JSON/XML are often used. Serializable is convenient for simple cases but has performance drawbacks.

What is serialization? — Android - sobes.tech