Kotlin JSON to Data class - JSON Serialization with Jackson Library

Published September 28, 2020


In 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 the Jackson  library.

Convert JSON to Data class Kotlin

 

What is Data class in kotlin?

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 Jackson dependency
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.+"

 

 

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 jacksonMapper= jacksonObjectMapper()
val jsonString=jacksonMapper.writeValueAsString(Test(1,"JackSon"))
print(jsonString)

}

 

This will print below the converted JSON string

{"id":1,"name":"JackSon"}

 

Convert JSON String to Data class

To convert JSON String to Data class we need to apply the below code 

 

fun convertJSONTOData()
{
    
val jacksonMapper= jacksonObjectMapper()
val testObject=jacksonMapper.readValue("{\"id\":1,\"name\":\"JackSon\"}",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 Jackson library

 

Learn How to convert JSON string to Data class in kotlin with GSON library

 

Tags: JSON Serialization, Data class, Jackson Mapping


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1934 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions