Updated March 31, 2023
Introduction to Kotlin Serialization
The kotlin serialization is the technique and process used to convert the application data with the specified format, and that can be transferred across the network, and it will be stored in the database or the external file. It may be any format like JSON, xml and it follows the protocol buffers. Here kotlin have the data serialization tools available in a separate component like “kotlinx.serialization” that package consists of the gradle plugins installed at the runtime libraries. The compile-time, type-safe mechanism for converting the objects into the data formats with a multi-platform supported environment.
Syntax of Kotlin Serialization
The kotlin language has many default classes, methods, variables, and other keywords used to implement the mobile-based application. Serialization is the process of converting the object to the data stream, and it is used to store it as a separate file.
@Serializable
data class className{
val name1: datatype
val name2: datatype
--------some declaration and logic codes---
}
fun main()
{
----Some main function codes depends on the above data class and the methods---
}
The above code is the basic syntax for creating and utilizing the serializable in kotlin language. We can use it anywhere on the programming codes, which depends on the requirement.
How does Serialization work in Kotlin?
Serialization is the process of converting the object data to the application data, and it can be stored with the separate file by using the format like json and xml etc. The kotlin has built-in functions, and it is completely used with the multi-platform supported used with the kotlin/native and kotlin/js. When we use non-kotlin type based file formats like json or xml based parser libraries would be suffered from some type of erasure data, and it could be the generic data type loses, so it should be avoided with the help of token type as the parameter in their serialization and deserialization functions.
We used other serialization techniques like polymorphic serialization, string customizability, framework integration and multi-format future types. Serialization is ignored and use the optional fields, and it can be used to adjust the default values, and it should be overridden for the JSON value format. In kotlin language, the new native standard serialization library was more similar to the java language concept like reflections used with the Android development. So the process of decomposing the inputs into the file stream for storing the datas that will be the encoded format. The encoder conversion is to be considered with another desired format for storing, processing and transforming datas into the other formats, which is on a similar requirement.
Examples of Kotlin Serialization
Given below are the examples of Kotlin Serialization:
Example #1
Code:
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.*
import kotlinx.serialization.*
import java.util.Base64
@Serializable
class first(val n: String, @SerialName("lang") val lang: String)
{
fun demo()
{
val sn="Its the first string"
var ml = mutableListOf<String>()
ml.add("First Element is:Siva")
ml.add("Second Element is :Raman")
ml.add("Third Element is :Siva Raman")
ml.add("Fourth Element is :Arun")
ml.add("Fifth Element is :Kumar")
var ma = mutableListOf<String>("Welcome To My Domain","Siva")
var mb = mutableListOf<String>("Welcome To My Domain","Raman")
var mc = mutableListOf<String>("Welcome To My Domain","SivaRaman")
println("Thank you users your first set of mutable list datas are:")
for(vars in ml){
println(vars)
}
println("Thank you users your second set of mutable list datas are:")
println(ml[2])
ml.add(2,"Sachin")
println(" We can modify the first set mutable list ml.add(2,\"Sachin\")")
for(vars in ml){
println(vars)
}
ml.add("Rajdurai")
println("Again we can add the list values ml.add(\"Rajdurai\")")
for(vars in ml){
println(vars)
}
ml.addAll(1,mb)
println("We can add all the list values to single list: ml.addAll(1,mb)")
for(vars in ml){
println(vars)
}
ml.addAll(ma)
println("We can add all the values and make it to the single list: ml.addAll(ma)")
for(vars in ml){
println(vars)
}
ml.remove("Salman")
println("We can remove the specified values: ml.remove(\"Salman\")")
for(vars in ml){
println(vars)
}
}
}
fun main() {
val data = first("kotlinx.serialization", "Kotlin")
var ref=first("Thank you for spenting the time with the serialization concept","Kotlin with Maven")
var dt=ref.demo()
var s= arrayOf(dt)
for(ars in sequenceOf(s))
{
println(ars)
}
var l= listOf(data)
println(s)
println(l)
val str = "Welcome To My Domain its the first example that related to the kotlin serialization"
val out: String = Base64.getEncoder().encodeToString(str.toByteArray())
println(out)
}
Output:
The above example is the basic example that can be related to the @Serializable annotation, and it operates the class as serialized one, and it is operated in the main method to complete the operations.
Example #2
Code:
import kotlinx.serialization.*
import kotlinx.serialization.*
import java.util.Date
import java.text.SimpleDateFormat
@Serializable
class Test() {
var age: Int = 0
var name: String = ""
var sex: String = ""
fun demo2(){
val s="32,Siva, male"
println(s)
}
}
enum class Second(var sec: String) {
demo("first method"){
override fun exam() {
println("Java is the higher leve language")
}
},
demo1("second method"){
override fun exam() {
println("C, C++ is the middle level language")
}
},
demo2("third method"){
override fun exam() {
println("dotnet is the high level language")
}
};
abstract fun exam()
fun demo1(stringValue: String): String{
return "Welcome"
}
}
fun main()
{
val d = Test()
var s=d.demo2()
println(SimpleDateFormat("yyyy-MM-ddX").parse("2021-06-07+00"))
println("Welcome To My Domain its the second example that relateded to the kotlin serialization, $s")
}
Output:
In the second example, we used the serializable concept with additional enums for declaring the different methods that can be executed on the main with serializable class.
Example #3
Code:
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
@Serializable
@SerialName("Building")
class Building(val structure: String){
var s1="Pyramid"
var s2="V-Structure"
var s3="Fire-Resistive"
var s4="Hut"
var s5="Wood frame"
}
@Serializable
@SerialName("Types")
class Types<T>(val details: T)
fun main() {
val res = "Welcome To My Domain its the third example that related to the kotlin serialization"
println(res)
var out=Building("Eiffel Tower")
println(out)
}
Output:
In the final example, we used @Serializable, and @SerialName are the two annotations that can be used to execute the serialized operations on both classes. Therefore, we created the two classes, and each class have assigned the SerialName annotation and Serializable.
Conclusion
In kotlin language, serialization is one of the concepts, and it is used to encode the datas so it’s encrypted the user inputs and using the de-serialization it can be decrypted. So it has different built-in methods, and it is used to perform the operation at the application level based on the requirement.
Recommended Articles
This is a guide to Kotlin Serialization. Here we discuss the introduction, syntax and working of serialization in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –