Sobes.tech
Junior

What is serialization and parsing of objects in Android?

sobes.tech AI

Answer from AI

Serialization is the process of converting an object into a stream of bytes for storage (e.g., in a file or database) or transmission (e.g., over a network).

Parsing (or deserialization) is the reverse process: restoring an object from a byte stream.

In Android, Serializable or Parcelable are most commonly used for these purposes.

Serializable (standard Java interface): Easy to use (just implement the interface), but slower than Parcelable and creates many temporary objects.

// Example of Serializable
import java.io.Serializable;

public class MySerializableObject implements Serializable {
    private static final long serialVersionUID = 1L; // Recommended to specify
    private String name;
    private int age;

    public MySerializableObject(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters and setters
}

Parcelable (Android-specific interface): Faster and more efficient than Serializable, as it is optimized for IPC (Inter-Process Communication). Requires more code to implement.

// Example of Parcelable
import android.os.Parcel;
import android.os.Parcelable;

public class MyParcelableObject implements Parcelable {
    private String name;
    private int age;

    public MyParcelableObject(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Constructor for deserialization
    protected MyParcelableObject(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }

    // Creator for creating instances from Parcel
    public static final Creator<MyParcelableObject> CREATOR = new Creator<MyParcelableObject>() {
        @Override
        public MyParcelableObject createFromParcel(Parcel in) {
            return new MyParcelableObject(in);
        }

        @Override
        public MyParcelableObject[] newArray(int size) {
            return new MyParcelableObject[size];
        }
    };

    @Override
    public int describeContents() {
        return 0; // Always 0 for most objects
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }

    // Getters and setters
}

Comparison:

Feature Serializable Parcelable
Interface java.io.Serializable android.os.Parcelable
Performance Slower Faster
Ease of Use Easier (less code) Harder (more code)
Usage General Java Android (IPC, Bundles, Intents)
Object Creation More temporary objects Less temporary objects

Parcelable is preferred for passing data between Android app components (e.g., via Intent or Bundle).