kotlin jason 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 json

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
class MyJsonClass(val name: String, val optionalInt: Int = 5)

fun main() {
  val jsonToEncode = MyJsonClass( "Alice", 10 )
  val encodedJson  = Json.encodeToString( jsonToEncode )
  val decodedJson  = Json.decodeFromString<MyJsonClass>( jsonString )
}