This post will discuss how to serialize and deserialize objects in Kotlin.

Serialization is the process of converting an object into a sequence of bytes or a string, and deserialization is the process of rebuilding that sequence into a new object. There are several ways to persist an object in Kotlin.

1. Using Serializable Interface

The idea is to implement the Serializable interface, which causes serialization to be automatically handled by Kotlin. Then to convert the object into a serialized form, use writeObject() function from ObjectOutputStream class, and to recreate a completely new object from the bytes, use readObject() function. Following is a simple example demonstrating this:

Download  Run Code

Output:

Student(name='John Snow', age=25, subjects=[Physics, Maths, Biology, Geography])

2. Using Google’s Gson library

We can even perform serialization and deserialization of Kotlin objects using the Gson library. Gson provide functions toJson() and fromJson() to convert Kotlin objects to their JSON representation and vice-versa. Gson uses reflection behind the scenes and hence does not require any additional modifications to the corresponding class.

Download Code

Output:

Object to JSON string:
 
{"name":"Peter Parker","student":{"subjects":["Maths","Physics"],"id":"Peter_Parker_12"},"age":12}
 
JSON string to Object:
 
Person(name=Peter Parker, age=12, student=Student(id=Peter_Parker_12, subjects=[Maths, Physics]))

3. Using Jackson library

Similar to the Gson library, we can use the high-performance Jackson library to convert Kotlin objects to their JSON representation and then back to an equivalent Kotlin object.

We can use the writeValueAsString() and readValue() functions from the ObjectMapper class to convert Kotlin objects to JSON string and vice-versa. Note that, unlike Gson, Jackson requires the class to have a no-args constructor for instantiating from the JSON object. If no-args constructor is not present, org.codehaus.jackson.map.JsonMappingException exception will be thrown.

Download Code

Output:

Object to JSON string:
 
{"name":"Peter Parker","age":12,"student":{"id":"Peter_Parker_12","subjects":["Maths","Physics"]}}
 
JSON string to Object:
 
Person(name=Peter Parker, age=12, student=Student(id=Peter_Parker_12, subjects=[Maths, Physics]))

That’s all about serializing and deserializing objects in Kotlin.