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) val json = """{ "id": null }"""val entity = gson.fromJson(json, Entity::class.java)entity.id // <- Throws NPE

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:

@Kson
data class Entity(val id: Int)

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

@KsonFactory
object FactoryProvider {
get() = KsonFactoryProvider() // generated class
}
val gson = GsonBuilder()
.registerTypeAdapterFactory(FactoryProvider.get())
.create()

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

Love podcasts or audiobooks? Learn on the go with our new app.

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
Anatolii Afanasev

Anatolii Afanasev

Senior Android Developer at Agoda

More from Medium

Lost in Java Time with Android

AspectJ + Gradle — Retry Java Method on exception

Classifying categorical data in Weka via the API

Is Gradle hard to learn ?