Skip to main content

How to handle custom serialization and deserialization logic using GSON in Kotlin Android

How to handle custom serialization and deserialization logic using GSON in Kotlin Android.

Serialization and deserialization are important processes in software development, especially when working with data interchange formats like JSON. Gson is a popular library in the Android ecosystem for converting Java objects to JSON and vice versa.

In some cases, you may need to customize the serialization and deserialization logic for certain fields or objects. This can be achieved by implementing custom serializers and deserializers in Gson. In this tutorial, we will explore how to handle custom serialization and deserialization logic using Gson in Kotlin Android.

Step 1: Add Gson Dependency

To get started, you need to add the Gson dependency to your project. Open the build.gradle file of your app module and add the following line to the dependencies block:

implementation 'com.google.code.gson:gson:2.8.7'

Sync the project to ensure the dependency is downloaded and available for use.

Step 2: Create a Custom Serializer

To create a custom serializer, you need to implement the JsonSerializer interface provided by Gson. This interface has a single method serialize() that you need to override.

Let's say we have a Person class with a Date field representing the person's birthdate. We want to serialize the birthdate as a Unix timestamp (long value) instead of the default Date object. Here's an example implementation of a custom serializer for the Person class:

import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import java.lang.reflect.Type
import java.util.Date

class PersonSerializer : JsonSerializer<Person> {
override fun serialize(src: Person?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
val jsonObject = JsonObject()
jsonObject.addProperty("name", src?.name)
jsonObject.addProperty("birthdate", src?.birthdate?.time)
return jsonObject
}
}

In the serialize() method, we create a new JsonObject, add the person's name using addProperty(), and serialize the birthdate as a Unix timestamp using src?.birthdate?.time.

Step 3: Register the Custom Serializer

To use the custom serializer, you need to register it with Gson. In your code, create a Gson instance and register the custom serializer using the registerTypeAdapter() method.

val gson = GsonBuilder()
.registerTypeAdapter(Person::class.java, PersonSerializer())
.create()

In this example, we register the PersonSerializer for the Person class.

Step 4: Serialize an Object

Now that we have registered the custom serializer, we can serialize a Person object using Gson. Here's an example:

val person = Person("John Doe", Date())
val json = gson.toJson(person)

The toJson() method converts the person object to JSON using the custom serializer we provided.

Step 5: Create a Custom Deserializer

Similar to custom serialization, you can also create custom deserializers by implementing the JsonDeserializer interface. This interface has a single method deserialize() that you need to override.

Let's continue with the Person example and assume that the birthdate is stored as a Unix timestamp in the JSON. We want to deserialize it back to a Date object. Here's an example implementation of a custom deserializer for the Person class:

import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonDeserializationContext
import java.lang.reflect.Type
import java.util.Date

class PersonDeserializer : JsonDeserializer<Person> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Person {
val jsonObject = json?.asJsonObject
val name = jsonObject?.get("name")?.asString
val birthdate = Date(jsonObject?.get("birthdate")?.asLong ?: 0L)
return Person(name, birthdate)
}
}

In the deserialize() method, we extract the name and birthdate from the JSON object and create a new Person object.

Step 6: Register the Custom Deserializer

To use the custom deserializer, you need to register it with Gson similar to the custom serializer. In your code, create a Gson instance and register the custom deserializer using the registerTypeAdapter() method.

val gson = GsonBuilder()
.registerTypeAdapter(Person::class.java, PersonDeserializer())
.create()

In this example, we register the PersonDeserializer for the Person class.

Step 7: Deserialize JSON to an Object

Now that we have registered the custom deserializer, we can deserialize JSON to a Person object using Gson. Here's an example:

val json = "{\"name\":\"John Doe\",\"birthdate\":1636473600000}"
val person = gson.fromJson(json, Person::class.java)

The fromJson() method converts the JSON string to a Person object using the custom deserializer we provided.

Conclusion

In this tutorial, you learned how to handle custom serialization and deserialization logic using Gson in Kotlin Android. We explored the steps to create custom serializers and deserializers, and how to register them with Gson. By implementing custom logic, you can have fine-grained control over the serialization and deserialization process for specific fields or objects.