Serialization strategies
Serialization Strategies Deep Dive¶
Overview¶
Serialization converts Kotlin objects to/from JSON. Performance and flexibility vary across libraries.
Core Concepts¶
Serialization Libraries¶
Gson (Google): - Reflection-based - Flexible, lenient parsing - No compile-time checks - mature, widely used
Moshi (Square): - Reflection + type adapters - Customizable parsing - Better error messages - faster than Gson
Kotlin Serialization (JetBrains): - Compiler plugin generates code - No reflection needed - Compile-time safety - Newer, growing adoption
Internal Implementation¶
Gson vs Moshi vs Kotlin Serialization Comparison¶
| Aspect | Gson | Moshi | Kotlin Serialization |
|---|---|---|---|
| Speed | 250ฮผs | 150ฮผs | 50ฮผs |
| Reflection | Yes | Partial | No |
| Type Safety | Runtime | Runtime | Compile-time |
| Error Messages | Good | Excellent | Good |
| Setup | Easy | Medium | Medium |
Request/Response Flow¶
- OkHttp receives response bytes
- Retrofit converter deserializes
- Object passed to collecting flow/callback
Code Examples¶
Custom Gson Serializer¶
data class User(val id: Int, val createdAt: Date)
class DateSerializer : JsonSerializer<Date>,
JsonDeserializer<Date> {
private val fmt = SimpleDateFormat("yyyy-MM-dd")
override fun serialize(src: Date?, typeOfSrc: Type?,
context: JsonSerializationContext?) = JsonPrimitive(fmt.format(src))
override fun deserialize(json: JsonElement?, typeOfT: Type?,
context: JsonDeserializationContext?) =
fmt.parse(json?.asString ?: "")
}
Common Interview Questions¶
Q: Why is Kotlin Serialization faster? A: Compiler generates code instead of using reflection at runtime.
Q: Should I migrate from Gson? A: Only if performance is critical. Gson ecosystem is larger.
Production Considerations¶
Backwards Compatibility¶
When API adds fields:
@Serializable
data class User(
val id: Int,
val name: String,
@Transient // skip serialization
val newFeature: String = "default"
)
Performance Insights¶
Caching Serializers¶
Create serializers once:
val gson = GsonBuilder()
.registerTypeAdapter(...)
.build()
// reuse
val user = gson.fromJson(json, User::class.java)
Senior-Level Insights¶
Version Stability¶
Track API schema versions:
// v1 field removed, v2 added
if (apiVersion >= 2) {
useNewField()
}