Skip to main content

How to handle date and time formats while serializing and deserializing JSON using GSON in Kotlin Android

How to handle date and time formats while serializing and deserializing JSON using GSON in Kotlin Android.

Here's a step-by-step tutorial on how to handle date and time formats while serializing and deserializing JSON using GSON in Kotlin for Android.

Step 1: Add GSON Dependency

First, you need to add the GSON dependency to your project. Open your app-level build.gradle file and add the following line in the dependencies block:

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

Step 2: Create a Data Class

Next, create a data class that represents the structure of your JSON data. Make sure to annotate any date or time fields with the @SerializedName annotation to match the JSON key:

import com.google.gson.annotations.SerializedName
import java.util.Date

data class MyData(
@SerializedName("id") val id: Int,
@SerializedName("name") val name: String,
@SerializedName("created_at") val createdAt: Date
)

Step 3: Create a Custom Date Serializer

To handle date and time formats, you need to create a custom serializer. Create a new Kotlin class and name it CustomDateSerializer. Implement the JsonSerializer interface and override the serialize method. In this method, you can format the date according to your desired format:

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.text.SimpleDateFormat
import java.util.Date

class CustomDateSerializer : JsonSerializer<Date> {
private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

override fun serialize(
src: Date?,
typeOfSrc: Type?,
context: JsonSerializationContext?
): JsonElement {
return JsonPrimitive(dateFormat.format(src))
}
}

Step 4: Create a Custom Date Deserializer

Similarly, you need to create a custom deserializer to handle the deserialization of dates. Create another Kotlin class named CustomDateDeserializer and implement the JsonDeserializer interface. Override the deserialize method and parse the date string into a Date object:

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

class CustomDateDeserializer : JsonDeserializer<Date> {
private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): Date {
val dateString = json?.asString
return try {
dateFormat.parse(dateString)
} catch (e: ParseException) {
Date()
}
}
}

Step 5: Register Custom Serializer and Deserializer

Now, you need to register the custom serializer and deserializer with GSON. When creating a GSON instance, use the GsonBuilder and call the registerTypeAdapter method to specify the type and the custom serializer or deserializer:

import com.google.gson.GsonBuilder

val gson = GsonBuilder()
.registerTypeAdapter(Date::class.java, CustomDateSerializer())
.registerTypeAdapter(Date::class.java, CustomDateDeserializer())
.create()

Step 6: Serialize and Deserialize JSON

With the custom serializer and deserializer registered, you can now serialize and deserialize JSON data that contains date and time fields. Here's an example of how to do it:

val myData = MyData(1, "John Doe", Date())

// Serialize to JSON
val json = gson.toJson(myData)

// Deserialize from JSON
val deserializedData = gson.fromJson(json, MyData::class.java)

That's it! You have successfully handled date and time formats while serializing and deserializing JSON using GSON in Kotlin for Android.