- Serialize and deserialize objects in Kotlin
- 1. Using Serializable Interface
- 2. Using Google’s Gson library
- 3. Using Jackson library
- Serialization
- Libraries
- Formats
- Example: JSON serialization
- Converting Kotlin Data Class from JSON using GSON
- 1. Overview
- 2. Maven Dependency
- 3. Kotlin Data Class
- 4. Converting from Data Class to JSON String
- 5. Converting from JSON String to a Data Class
- 6. Conclusion
- Kotlin – Convert Object to/from JSON with Jackson 2.x
- I. Technology
- II. Overview
- 1. Goal
- 2. Steps to do
- III. Practice
- 0. Person Class
- 1. Json String/URL/File to Object
- 2. Object to Json String/File
- IV. More Practice
- 1. Json array format to List
- 2. Json to Map
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:
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.
Output:
Object to JSON string:
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.
Serialization
Serialization is the process of converting data used by an application to a format that can be transferred over a network or stored in a database or a file. In turn, deserialization is the opposite process of reading data from an external source and converting it into a runtime object. Together they are an essential part of most applications that exchange data with third parties.
Some data serialization formats, such as JSON and protocol buffers are particularly common. Being language-neutral and platform-neutral, they enable data exchange between systems written in any modern language.
In Kotlin, data serialization tools are available in a separate component, kotlinx.serialization. It consists of several parts: the org.jetbrains.kotlin.plugin.serialization Gradle plugin, runtime libraries, and compiler plugins.
Compiler plugins, kotlinx-serialization-compiler-plugin and kotlinx-serialization-compiler-plugin-embeddable , are published directly to Maven Central. The second plugin is designed for working with the kotlin-compiler-embeddable artifact, which is the default option for scripting artifacts. Gradle adds compiler plugins to your projects as compiler arguments.
Libraries
kotlinx.serialization provides sets of libraries for all supported platforms – JVM, JavaScript, Native – and for various serialization formats – JSON, CBOR, protocol buffers, and others. You can find the complete list of supported serialization formats below.
All Kotlin serialization libraries belong to the org.jetbrains.kotlinx: group. Their names start with kotlinx-serialization- and have suffixes that reflect the serialization format. Examples:
- org.jetbrains.kotlinx:kotlinx-serialization-json provides JSON serialization for Kotlin projects.
- org.jetbrains.kotlinx:kotlinx-serialization-cbor provides CBOR serialization.
Platform-specific artifacts are handled automatically; you don’t need to add them manually. Use the same dependencies in JVM, JS, Native, and multiplatform projects.
Note that the kotlinx.serialization libraries use their own versioning structure, which doesn’t match Kotlin’s versioning. Check out the releases on GitHub to find the latest versions.
Formats
kotlinx.serialization includes libraries for various serialization formats:
Note that all libraries except JSON serialization ( kotlinx-serialization-json ) are Experimental, which means their API can be changed without notice.
There are also community-maintained libraries that support more serialization formats, such as YAML or Apache Avro. For detailed information about available serialization formats, see the kotlinx.serialization documentation.
Example: JSON serialization
Let’s take a look at how to serialize Kotlin objects into JSON.
Before starting, you’ll need to configure your build script so that you can use Kotlin serialization tools in your project:
- Apply the Kotlin serialization Gradle plugin org.jetbrains.kotlin.plugin.serialization (or kotlin(«plugin.serialization») in the Kotlin Gradle DSL).
Converting Kotlin Data Class from JSON using GSON
As a seasoned developer, you’re likely already familiar with Spring. But Kotlin can take your developer experience with Spring to the next level!
- Add new functionality to existing classes with Kotlin extension functions.
- Use Kotlin bean definition DSL.
- Better configure your application using lateinit.
- Use sequences and default argument values to write more expressive code.
By the end of this talk, you’ll have a deeper understanding of the advanced Kotlin techniques that are available to you as a Spring developer, and be able to use them effectively in your projects.
1. Overview
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.
2. Maven Dependency
Before we start, let’s add Gson to our pom.xml:
com.google.code.gson gson 2.8.5
3. Kotlin Data Class
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:
4. Converting from Data Class to JSON String
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, """""")
In this example, we are using Assert to check if the output from Gson matches our expected value.
5. Converting from JSON String to a Data Class
Of course, sometimes we need to convert from JSON to data objects:
var jsonString = """"""; 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.
6. Conclusion
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.
All examples, as always, can be found over on GitHub.
Kotlin – Convert Object to/from JSON with Jackson 2.x
This tutorial shows you how to use Jackson 2.x to convert Kotlin object to/from JSON.
I. Technology
– Java 1.8
– Kotlin 1.1.2
– Maven 3.5.1
II. Overview
1. Goal
Convert JSON string/JSON file/JSON url to Person(name:String,age:Int,messages:List) Kotlin Object, then convert Person object to JSON string/JSON file.
2. Steps to do
org.jetbrains.kotlin kotlin-stdlib 1.1.2 com.fasterxml.jackson.module jackson-module-kotlin 2.8.8
– import com.fasterxml.jackson.module.kotlin.*
– use ObjectMapper instance:
val mapper = jacksonObjectMapper() // Json String/URL/File to Object var person: Person = -> mapper.readValue(String) -> mapper.readValue(URL) -> mapper.readValue(File) // Object to Json String/File var jsonStr = -> mapper.writeValueAsString(Person) -> mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Person) -> mapper.writeValue(File, Person) -> mapper.writerWithDefaultPrettyPrinter().writeValue(File, Person)
III. Practice
0. Person Class
package com.javasampleapproach.jsonstring data class Person(val name: String, val age: Int, val messages: List)
1. Json String/URL/File to Object
package com.javasampleapproach.jsonstring import com.fasterxml.jackson.module.kotlin.* import java.net.URL import java.io.File fun main(args: Array) < val json = """""" val mapper = jacksonObjectMapper() println("=== JSON to Kotlin Object ===") println("1- read String") var person: Person = mapper.readValue(json) println(person) println("2- read URL") person = mapper.readValue(URL("https://ozenero.com/wp-content/uploads/2017/08/person.json")) println(person) println("3- read File") /* content of person.json < "name" : "Kolineer", "age" : 28, "messages" : [ "message AA", "message BB" ] >*/ person = mapper.readValue(File("person.json")) println(person) >
=== JSON to Kotlin Object === 1- read String Person(name=Kolineer, age=26, messages=[message a, message b]) 2- read URL Person(name=Kolineer, age=27, messages=[message A, message B]) 3- read File Person(name=Kolineer, age=28, messages=[message AA, message BB])
2. Object to Json String/File
package com.javasampleapproach.jsonstring import com.fasterxml.jackson.module.kotlin.* import java.io.File fun main(args: Array) < val mapper = jacksonObjectMapper() println("=== Kotlin Object to JSON ===") person = Person("Kolineer Master", 30, listOf("I am Kotlin Master", "still learning Kotlin")) println("1- String") var jsonStr = mapper.writeValueAsString(person) println(jsonStr) println("2- Formatted String") jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person) println(jsonStr) println("3- File ->manually check file for result") mapper.writerWithDefaultPrettyPrinter().writeValue(File("newPerson.json"), person) >
=== Kotlin Object to JSON === 1- String 2- Formatted String < "name" : "Kolineer Master", "age" : 30, "messages" : [ "I am Kotlin Master", "still learning Kotlin" ] >3- File -> manually check file for result
IV. More Practice
1. Json array format to List
val jsonList = «»»[, ]»»» var personList: List = mapper.readValue(jsonList) personList.forEach
Person(name=Kolineer, age=26, messages=[message a, message b]) Person(name=Kolineer Master, age=30, messages=[I am Kotlin Master, still learning Kotlin])
2. Json to Map
val json = «»»»»» var personMap: Map = mapper.readValue(json) personMap.forEach
name=Kolineer age=26 messages=[message a, message b]