1. Overview

In this short tutorial, we’ll discuss how to convert a data class in Kotlin to JSON string and vice versa using Gson Java library.

2. Maven Dependency

Before we start, let’s add Gson to our pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

3. Kotlin Data Class

First of all, let’s create a data class that we’ll convert to JSON string in the later parts of the article:

data class TestModel(
    val id: Int,
    val description: String
)

The TestModel class consists of 2 attributes: id and name. Therefore, the JSON string we expect from Gson would look like:

{"id":1,"description":"Test"}

4. Converting from Data Class to JSON String

Now, we can use Gson to convert objects of TestModel class to JSON:

var gson = Gson()
var jsonString = gson.toJson(TestModel(1,"Test"))
Assert.assertEquals(jsonString, """{"id":1,"description":"Test"}""")

In this example, we are using Assert to check if the output from Gson matches our expected value.

5. Converting from JSON String to a Data Class

Of course, sometimes we need to convert from JSON to data objects:

var jsonString = """{"id":1,"description":"Test"}""";
var testModel = gson.fromJson(jsonString, TestModel::class.java)
Assert.assertEquals(testModel.id, 1)
Assert.assertEquals(testModel.description, "Test")

Here, we’re converting the JSON string to a TestModel object by telling Gson to use TestModel::class.java as Gson is a Java library and only accepts Java class.

Finally, we test if the result object contains the correct values in the original string.

6. Conclusion

In this quick article, we have discussed how to use Gson in Kotlin to convert a Kotlin data class to JSON string and vice versa.

All examples, as always, can be found over on GitHub.

Comments are closed on this article!