
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 19, 2024
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.
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>
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"}
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.
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.
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.