kotlin Gson code example

Example: gson kotlin

// Maven declare in pom.xml:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
// Or Gradle / Android
dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}
  
data class TestModel(
    val id: Int,
    val description: String
)

// from Data Class to JSON String    json: {"id":1,"description":"Test"}
var gson = Gson()
var jsonString = gson.toJson(TestModel(1,"Test"))

// from JSON String to a Data Class
var jsonString = """{"id":1,"description":"Test"}""";
var testModel = gson.fromJson(jsonString, TestModel::class.java)