Sobes.tech
Junior — Middle

Is it possible to use alternative serialization methods for storing classes besides the Serializable interface?

sobes.tech AI

Answer from AI

Yes, besides the Serializable interface in Android, alternative serialization methods can be used for storing classes:

  • Parcelable — a more efficient and recommended way of serialization in Android. It allows faster serialization of objects for passing between components.

  • JSON or other formats (e.g., Gson, Moshi) — serializing an object into a JSON string and back. Convenient for storing or transmitting data but requires additional processing.

  • ProtoBuf (Protocol Buffers) — a binary serialization format, efficient and compact, often used for network communication.

  • Custom serialization — you can implement your own methods for writing and reading data, for example, through ByteBuffer or other mechanisms.

Example of Parcelable:

import android.os.Parcel
import android.os.Parcelable

 data class User(val name: String, val age: Int) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString() ?: "",
        parcel.readInt()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(name)
        parcel.writeInt(age)
    }

    override fun describeContents() = 0

    companion object CREATOR : Parcelable.Creator<User> {
        override fun createFromParcel(parcel: Parcel) = User(parcel)
        override fun newArray(size: Int) = arrayOfNulls<User?>(size)
    }
}