Describe a scenario where using a custom type adapter with Gson or Moshi would be necessary and beneficial. Implement a simple example.

Android interview question for Advanced practice.

Answer

A custom type adapter is beneficial when your JSON data doesn't directly map to a standard Kotlin data class. For example, if your JSON uses a non-standard date format or contains nested objects with complex relationships, a custom type adapter allows you to handle the serialization and deserialization process in a way that aligns with your specific needs. Here's an example showing a custom adapter for a date field using Gson: kotlin import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.text.SimpleDateFormat import java.util. data class MyData(val date: Date) class DateTypeAdapter : TypeAdapter<Date() { private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault()) override fun write(out: JsonWriter, value: Date?) { out.value(dateFormat.format(value)) } override fun read(reader: JsonReader): Date { return dateFormat.parse(reader.nextString()) } } val gson = GsonBuilder().registerTypeAdapter(Date::class.java, DateTypeAdapter()).create() This adapter converts dates to and from the specified format. Similar logic can be applied to Moshi and Kotlinx.serialization.

Explanation

Custom type adapters provide a powerful mechanism for extending the JSON library's capabilities and handling complex data structures.

Related Questions