1// JSON Kotlin with GSON
2// Maven declare in pom.xml:
3<dependency>
4 <groupId>com.google.code.gson</groupId>
5 <artifactId>gson</artifactId>
6 <version>2.8.5</version>
7</dependency>
8// Or Gradle / Android
9dependencies {
10 implementation 'com.google.code.gson:gson:2.8.5'
11}
12
13data class TestModel(
14 val id: Int,
15 val description: String
16)
17
18// from Data Class to JSON String json: {"id":1,"description":"Test"}
19var gson = Gson()
20var jsonString = gson.toJson(TestModel(1,"Test"))
21
22// from JSON String to a Data Class
23var jsonString = """{"id":1,"description":"Test"}""";
24var testModel = gson.fromJson(jsonString, TestModel::class.java)
1import kotlinx.serialization.decodeFromString
2import kotlinx.serialization.encodeToString
3import kotlinx.serialization.json.Json
4
5@Serializable
6class MyJsonClass(val name: String, val optionalInt: Int = 5)
7
8fun main() {
9 val jsonToEncode = MyJsonClass( "Alice", 10 )
10 val encodedJson = Json.encodeToString( jsonToEncode )
11 val decodedJson = Json.decodeFromString<MyJsonClass>( jsonString )
12}