Serialize and deserialize objects in Kotlin
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.io.* class Subjects : Serializable { private val subjects: Set<String> override fun toString(): String { return subjects.toString() } init { subjects = hashSetOf("Maths", "Physics", "Biology", "Geography") } } class Student(private val name: String, private val age: Int) : Serializable { private val subjects: Subjects = Subjects() override fun toString(): String { return "Student(name='$name', age=$age, subjects=$subjects)" } } fun main() { val student = Student("John Snow", 25) // Serialize val bos = ByteArrayOutputStream() val oos = ObjectOutputStream(bos) oos.writeObject(student) oos.flush() // deserialize val bytes = bos.toByteArray() val bis = ByteArrayInputStream(bytes) val ois = ObjectInputStream(bis) val clone = ois.readObject() as Student println(clone.toString()) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import com.google.gson.Gson class Student(private var id: String?) { private var subjects: Set<String>? = null init { subjects = mutableSetOf("Maths", "Physics") } override fun toString(): String { return "Student(id=$id, subjects=$subjects)" } } class Person(name: String, private var age: Int) { private var name: String? = name private var student: Student? = null init { student = Student(name.replace("\\s+".toRegex(), "_") + "_" + age.toString()) } override fun toString(): String { return "Person(name=$name, age=$age, student=$student)" } } fun main() { val person = Person("Peter Parker", 12) val gson = Gson() // Serialize val jsonString = gson.toJson(person) println("Object to JSON string:\n\n$jsonString") // Unserialize val p = gson.fromJson(jsonString, Person::class.java) println("\nJSON string to Object:\n\n$p") } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import org.codehaus.jackson.map.ObjectMapper class Student { var id: String? = null var subjects: Set<String>? = null constructor(id: String?) { this.id = id subjects = mutableSetOf("Maths", "Physics") } private constructor() {} override fun toString(): String { return "Student(id=$id, subjects=$subjects)" } } class Person { var name: String? = null var age = 0 var student: Student? = null constructor(name: String, age: Int) { this.name = name this.age = age student = Student(name.replace("\\s+".toRegex(), "_") + "_" + age.toString()) } private constructor() {} override fun toString(): String { return "Person(name=$name, age=$age, student=$student)" } } fun main() { val person = Person("Peter Parker", 12) val mapper = ObjectMapper() // Serialize val jsonString = mapper.writeValueAsString(person) println("Object to JSON string:\n\n$jsonString") // Unserialize val p = mapper.readValue(jsonString, Person::class.java) println("\nJSON string to Object:\n\n$p") } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)