KSON — auto-generate GSON adapters for Kotlin data classes

Kotlin data classes are super suitable as API entities. And it’s very easy to use them with GSON. But always keep in mind GSON uses ReflectiveTypeAdapterFactory by default which is not only slower, also it’s dangerous. Reflection doesn’t care about nullability of your properties. For example, this code will throw NullPointerException when you try to use entity.id in your code though it should throw it earlier during parsing JSON:

data class Entity(val id: Int) 

In order to solve this issue in Java, I used to use AutoValue with AutoGson extension but didn’t find any library for Kotlin (at that time). So I’ve decided to implement my own library and called it KSON.

Simply annotate your data class with Kson annotation and annotation processor will generate null-safe GSON type adapter for your entity class:

data class Entity(val id: Int)

Also, you can use KsonFactory annotation and register auto-generated type adapter factory which contains all generated adapters:

object FactoryProvider {
get() = KsonFactoryProvider() // generated class

As you see, KSON doesn’t need any extra work, just need to add 1 annotation to your class and that’s it! If you don’t want to use for some reason you can simply delete 1 line of code.

More info on Github: https://github.com/aafanasev/kson

Senior Android Developer at Agoda

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store