Table of Contents

    Book an Appointment

    HOW DID WE ENCOUNTER THE KOTLINX SERIALIZATION CUSTOM SERIALIZER CHALLENGE?

    While working on a core data-processing library for a high-traffic FinTech SaaS platform, we faced a critical architectural decision. The platform handled thousands of daily transactions and our backend relied heavily on Gson for JSON parsing. However, Gson’s reliance on runtime reflection was creating performance bottlenecks and preventing us from moving toward a Kotlin Multiplatform architecture. We decided to migrate to native Kotlin serialization.

    During this migration, we encountered a significant obstacle regarding default type adapters. In our legacy Gson implementation, we had a centralized configuration where we registered custom adapters globally for types like java.util.Date, Optional and various custom collections. When transitioning, we needed an equivalent kotlinx serialization custom serializer approach that would not require us to manually annotate thousands of fields across our massive legacy codebase.

    This challenge is common for teams dealing with large-scale refactoring. When organizations look to modernize, they often seek to hire kotlin developers for scalable data systems who understand the nuances of compile-time versus runtime serialization. This scenario inspired this article, aiming to help other engineering teams navigate the architectural shift from Gson’s reflection-based registry to Kotlinx’s compile-time safety.

    WHAT IS THE ARCHITECTURAL CONTEXT BEHIND THIS SERIALIZATION MIGRATION?

    In our FinTech use case, the API layer communicated with various legacy downstream services. We had strict formatting rules for dates, nullability and empty collections. With Gson, this was elegantly handled in a single dependency provider class using a builder pattern.

    Our legacy setup looked similar to this generic representation:

    fun legacyGsonBuilder(includeEmptyCollection: Boolean = false, serializeNulls: Boolean = true): GsonBuilder {
        val builder = GsonBuilder()
        builder.registerTypeAdapter(Boolean::class.java, BooleanAdapter())
        builder.registerTypeAdapter(Date::class.java, DateAdapter())
        builder.registerTypeHierarchyAdapter(Collection::class.java, CollectionAdapter(includeEmptyCollection))
        
        builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
        if (serializeNulls) {
            builder.serializeNulls()
        }
        return builder
    }
    

    We could simply inject this global configuration anywhere in the application. However, when we introduced Kotlinx serialization, we realized that the paradigm is fundamentally different. Kotlinx operates via a compiler plugin, meaning the serialization logic must be known and generated at compile time, completely eliminating the runtime reflection that Gson relies on.

    WHY DID THE GSON TO KOTLINX MIGRATION CAUSE ISSUES?

    The friction surfaced immediately when we tried to compile our existing Data Transfer Objects (DTOs). Because types like java.util.Date or java.util.Optional are external and not natively annotated with @Serializable, the Kotlinx compiler plugin threw errors.

    The official documentation suggested two immediate solutions, both of which presented severe symptoms of technical debt for a large legacy project:

    • Field-level annotations: We could annotate every single date or optional field with @Serializable(with = DateSerializer::class). For a codebase with thousands of DTOs, this was completely impractical and highly error-prone.
    • File-level annotations: We could use @file:UseSerializers(DateSerializer::class) at the top of every file containing these types. While better, it still created a massive maintenance headache. Any time a developer added a new DTO file, they had to remember to include the annotation or the build would fail.

    The core architectural oversight was assuming Kotlinx serialization offered a 1:1 drop-in replacement for Gson’s global runtime registry. We needed a strategy that respected Kotlinx’s compile-time constraints without halting our development velocity.

    WHAT WERE THE POTENTIAL APPROACHES TO SOLVE THIS SERIALIZATION DILEMMA?

    Before arriving at our final architecture, our dedicated remote engineering team evaluated multiple approaches. When enterprise clients hire backend developers for enterprise modernization, evaluating technical trade-offs is a critical part of the delivery process. We considered these solutions as well:

    HOW ABOUT A PURE CONTEXTUAL SERIALIZATION MODULE?

    Kotlinx provides a SerializersModule that allows you to define contextual serializers. You map a runtime class to a serializer, similar to Gson. However, the catch is that the properties inside your DTOs still need the @Contextual annotation. This centralized the logic but did not solve the annotation fatigue in the legacy classes.

    COULD WE USE WRAPPER TYPES OR VALUE CLASSES?

    We considered wrapping all external types into Kotlin inline value classes that were inherently serializable. This is a great Domain-Driven Design approach, but retrofitting this into a massive legacy codebase would require refactoring thousands of method signatures across the API layer.

    WHAT ABOUT CUSTOM GRADLE PLUGINS OR LINTERS?

    To avoid manual annotations, we looked into writing a custom Kotlin Symbol Processing (KSP) plugin or using a Detekt rule to automatically enforce or inject @file:UseContextualSerialization into all files within our DTO packages. This automated the maintenance but added complexity to our CI/CD pipeline.

    HOW DID WE IMPLEMENT THE FINAL KOTLINX SERIALIZATION CUSTOM SERIALIZER?

    We realized that a completely annotation-free global registry is impossible in Kotlinx without sacrificing the performance benefits of compile-time generation. Therefore, we chose a hybrid approach: defining a robust SerializersModule and applying package-level contextual serialization using a lightweight scripting approach during the migration.

    Here is how we structured the kotlinx serialization custom serializer configuration:

    import kotlinx.serialization.KSerializer
    import kotlinx.serialization.json.Json
    import kotlinx.serialization.modules.SerializersModule
    import kotlinx.serialization.modules.contextual
    import java.util.Date
    // Define the global module
    val globalSerializersModule = SerializersModule {
        contextual(Date::class, DateAsIsoStringSerializer)
        contextual(Optional::class, OptionalSerializer)
        // Register other legacy types here
    }
    // Create the configured Json instance
    val customJsonProvider = Json {
        serializersModule = globalSerializersModule
        encodeDefaults = true
        explicitNulls = true
        ignoreUnknownKeys = true
    }

    To solve the legacy codebase annotation problem, we wrote a one-time migration script that scanned our DTO packages and automatically prepended @file:UseContextualSerialization(Date::class, Optional::class) to the top of the files. For ongoing maintenance, we added a simple architecture test (using ArchUnit) that verified any class residing in the DTO package either used native Kotlin types or included the file-level annotation.

    This approach gave us the best of both worlds: centralized serializer definitions and compile-time safety, without forcing developers to manually track annotations.

    WHAT ARE THE CORE LESSONS FOR ENGINEERING TEAMS MODERNIZING SERIALIZATION?

    When you transition from runtime reflection to compile-time generation, the architectural mindset must change. Here are actionable insights for teams undergoing similar modernizations:

    • Understand Compile-Time vs. Runtime: Gson’s magic happens at runtime, which costs CPU cycles. Kotlinx’s magic happens at compile time, which requires explicitness. Embrace the explicitness for the sake of application performance.
    • Centralize Contextual Modules: Always use SerializersModule to manage your kotlinx serialization custom serializer logic. Never hardcode serializer references directly into DTOs unless absolutely necessary.
    • Automate Architectural Rules: Use tools like ArchUnit or Detekt to enforce serialization annotations across specific packages. This prevents human error when managing file-level configurations.
    • Migrate Away from Legacy Types: Serialization migrations are the perfect time to deprecate java.util.Date. Plan a phase to replace these with kotlinx.datetime for native compatibility.
    • Evaluate Resource Needs Early: Complex architectural refactoring requires deep language expertise. If your team is stretched thin, it may be the right time to hire software developer resources who specialize in large-scale system modernization.

    HOW DOES THIS IMPACT FUTURE MODERNIZATION EFFORTS?

    Moving from Gson to Kotlin native serialization is not just a syntax update; it is an architectural paradigm shift. By implementing a centralized kotlinx serialization custom serializer strategy and automating compliance across our legacy DTOs, we successfully removed reflection overhead, improved our API latency and paved the way for Kotlin Multiplatform integration.

    Our approach ensures that even when clients scale and hire app developer to create a mobile app consuming these APIs, the backend payload remains consistent, strict and highly performant. If your team is navigating complex architectural migrations or enterprise modernization, contact us to explore how our dedicated remote engineering teams can help accelerate your delivery.

    Social Hashtags

    #Kotlin #KotlinxSerialization #CustomSerializer #KotlinMultiplatform #GsonMigration #KotlinDevelopment #BackendDevelopment #SoftwareEngineering #LegacyModernization #ApplicationModernization #SoftwareArchitecture #JSONSerialization #FinTech #HireKotlinDevelopers #EnterpriseModernization

    Frequently Asked Questions

    Success Stories That Inspire

    See how our team takes complex business challenges and turns them into powerful, scalable digital solutions. From custom software and web applications to automation, integrations, and cloud-ready systems, each project reflects our commitment to innovation, performance, and long-term value.