KSON

General

Category
Free
Tag
Kotlin
License
Apache License, Version 2.0
Registered
May 18, 2018
Favorites
0
Link
https://github.com/aafanasev/kson
See also
Kotlinity
moshi-kotlin-ignore
KotlinMvpTemplate
Kotlet
Time

Additional

Language
Kotlin
Version
0.4 (May 25, 2018)
Created
May 14, 2018
Updated
Oct 7, 2018
Owner
Anatolii Afanasev (aafanasev)
Contributor
Anatolii Afanasev (aafanasev)
1
Activity
Badge
Generate
Download
Source code

Promotion

An annotation processor generates Gson TypeAdapter from Kotlin Data Classes

Motivation

By default, Gson uses reflection to read/write data from JSON. It's not only slow (benchmarks), also it breaks Kotlin's null-safe types.

For example:

// your entity class with non-nullable property
data class Entity(val id: Int)

// wrong response from server
val json = """{ "id": null }"""

// this won't throw error
val entity = gson.fromJson(json, Entity::class.java)

// throws NPE somewhere in runtime when you don't expect
entity.id

In order to avoid reflection, need to create a custom TypeAdapter for every entity class. It takes time, need to write boilerplate code, tests, etc. Here this library comes, it generates TypeAdapters automatically. You just need to register generated GsonTypeAdapterFactory in your GsonBuilder.

Usage

Add @Kson annotation to your data classes

@Kson
data class RoleEntity(
    val id: Int, 
    @SerializedName("roleName") val name: String
)

@Kson
data class UserEntity(
    val firstname: String,
    val lastname: String,
    val roles: List<RoleEntity>
)

// etc

Register generated TypeAdapterFactory

import com.aafanasev.kson.generated.KsonTypeAdapterFactory // generated factory

val gson = GsonBuilder()
    .registerTypeAdapterFactory(KsonTypeAdapterFactory())
    .create()

// gson.fromJson(...)

Limitations & Known issues

Since this is an early version there are some unsupported properties

@Kson
data class UnsupportedDataClass(
    @JsonAdapter(CustomAdapter::class) val id: String // custom type adapter
    val name: String = "no name" // default values
    val list: List<String?> // nullable generics
    val `natural name`: String // "natural names"
)

Installation

To add KSON to your project, add the following to your module's build.gradle:

repositories {
    jcenter()
}

dependencies {
    compile 'com.aafanasev:kson-annotation:<version>'   
    kapt 'com.aafanasev:kson-processor:<version>'
}