java - read - Kotlin Data Class from Json using GSON

kotlin read json file gson (2)

I have Java POJO class like this:

class Topic {
    long id;
    String name;

and I have a Kotlin data class Like this

 data class Topic(val id: Long, val name: String)

How to provide the json key to any variables of the kotlin data class like the @SerializedName annotation in java variables ?

Based on answer of Anton Golovin


  • Gson version: 2.8.5
  • Android Studio 3.1.4
  • Kotlin version: 1.2.60


Create any class data and inherit JSONConvertable interface

interface JSONConvertable {
     fun toJSON(): String = Gson().toJson(this)

inline fun <reified T: JSONConvertable> String.toObject(): T = Gson().fromJson(this,


Data class

data class User(
    @SerializedName("id") val id: Int,
    @SerializedName("email") val email: String,
    @SerializedName("authentication_token") val authenticationToken: String) : JSONConvertable


val json = "..."
val object = json.toObject<User>()


val json = object.toJSON()

Data class:

data class Topic(
  @SerializedName("id") val id: Long, 
  @SerializedName("name") val name: String, 
  @SerializedName("image") val image: String,
  @SerializedName("description") val description: String

to JSON:

val gson = Gson()
val json = gson.toJson(topic)

from JSON:

val json = getJson()
val topic = gson.fromJson(json,