gson kotlin adapter

An open source library to get the most out of Gson when coding in Kotlin.

Why we built it.

Gson is a widely-used tool, created by Google, for converting Java Objects into their JSON representation and vice versa. It's built for Java—the language of choice for Android developers for years. When Kotlin arrived, it quickly became the new language of choice, and newer tools like Moshi and KotlinX Serialization have been introduced to replace Gson. In many cases, for older apps, it's not a trivial task to migrate from one tool to the next. For apps using Gson, it's difficult to take advantage of all the benefits of Kotlin data classes; the root issue is that Gson does not call the primary constructor of the Kotlin data class.

Gson Kotlin Adapter is a TypeAdapterFactory that solves the root problem by ensuring the primary constructor of the Kotlin data class is invoked when deserializing JSON into a data class. This allows the app to utilize all of the benefits of Kotlin data classes.

How it works.

Normally when deserializing JSON to Kotlin, Gson hands the JSON to a reflection-based TypeAdapter which populates an empty class with the data. Gson Kotlin Adapter will step in before that happens, parse the JSON itself, and then pass those properties into the Kotlin class's primary constructor.

How to use it.

Gson Kotlin Adapter is simple to use: just add it to your instance of Gson.

Check out the project on GitHub for more details.

Built by Livefront.

Livefront is a digital product consultancy. We're trusted by some of the world's most admired companies to drive strategy, design, and engineering for their core digital experiences. They partner with us to move faster, think bigger, and design products people love.

Learn more