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:

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

val gson = GsonBuilder()

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

This article was originally posted on Medium.