kotlin read json object code example

Example 1: kotlin json

// JSON Kotlin with GSON
// 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)

Example 2: kotlin jsonobject from string

val data = JSONObject("""{"name":"test name", "age":25}""")