Norway


-  - The Android Arsenal – Kotlin -  - The Android Arsenal – Kotlin

An annotation processor generates GSON TypeAdapter from Classes

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

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"
)

Install

// add repository
repositories {
    maven {
        url 'https://dl.bintray.com/aafanasev/maven'
    }
}

// add dependency
compile 'com.aafanasev:kson-annotation:<version>'   
kapt 'com.aafanasev:kson-processor:<version>'



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here