Kotlin JSON to Data class - JSON Serialization with GSON Library
Last updated Sep 28, 2020In this post, we are going to learn how to convert JSON string Data class and vice versa in kotlin.
For this, we are going to use GSON library.
What is Data class in kotlin?
A data class is a class that only contains state and does not perform any operation.
By using this class we don't need to write any getter() and setter() methods in the class to access the state of the class.
Add dependencies
To Convert JSON to Data class or vice versa we need to add GSON dependency
implementation 'com.google.code.gson:gson:2.8.6'
|
Find maven dependency here
Create Kotlin Data class
First, we need to create a Data class, here we are creating a class named Test
data class Test(
val id:Int,val name:String
)
|
This Data class consist of two parameters id and name
Convert Data class to JSON String
To convert the Data class to JSON string we need to apply the below code for the Test class
fun convertDatatoJSON()
{
val gson=Gson()
val jsonString= gson.toJson(Test(1,"GSON"))
print(jsonString)
}
|
This will print below the converted JSON string
{"id":1,"name":"GSON"} |
Convert JSON String to Data class
To convert JSON String to Data class we need to apply the below code
fun convertJSONTOData()
{
val gson=Gson()
val testObject=gson.fromJson("{\"id\":1,\"name\":\"GSON\"}",Test::class.java);
print("Test ID =${testObject.id}")
}
|
this will print below the output
Test ID =1 |
Conclusion
In this post, we learned how to convert JSON string to Data class and vice versa in Kotlin with GSON library
Learn How to convert JSON string to Data class in kotlin with Jackson library
Tags: JSON Serialization, Data class, Jackson Mapping
Article Contributed By :
|
|
|
|
1591 Views |