- An
Object
in a computer memory consists of binary data that a computer can directly use it. Serialization
is the process of reducing theobject
into its primitive structure likeinteger
,array
,etc
in a manner that preserves that structure.Encoding
is a process of converting a serialized object into aoutput format
by following a specific set of rules.Class Object
-----serialization---->
Machine readable binary structure
-----encoding---->
Json/Xml structure
Class { int x, int y }
---->
{11011101,10011111}
---->
{"x":12312,"y":12233}
- After the serialization, We view it as a human redable format.
- The input data which is in human redable form which is
json/xml
isdeserialized
intoprimitives
and thendecoded
into objects. Json/Xml structure
-----deserialization---->
Primitives
-----decoding---->
Class Object
.
- There are support for primitive data types
Boolean
,Byte
,Short
,Int
,Long
,String
,Double
,Char
- Other types include
List
,enum
,set
,pair
etc
Moshi |
Gson |
KotlinSerialization |
---|---|---|
Uses code genaration | Uses reflection | Uses code generation, compiler plugin is used instead of annotation |
Faster runtime performance | Slow runtime performance | Good runtime performance |
Increased build time | build time is not increased | Fast build time |
- Moshi has more advanced features and provides a lower-level JSON API for maximum control
- Kotlin Serialization is also used in KMP(Kotlin Multi Platform)
- Kotlin Serialization is also compatible with unsigned integer types, value classes and sealed classes out-of-the-box.
- Kotlin Serialization is slightly better than Moshi and much better than GSON, But the due to teh extra kotlin powered language syntax sugar, this library is a good choice to use in development.
One of the normal usecases we face is converting Model
objects into JSON
string
- Model object
@Serializable
data class StudentInfo(
@SerialName("name")
val studentName: String,
@SerialName("age")
val studentAge: Int,
)
- Converting the model object to json string
fun main() {
val studentModel = StudentInfo("Ramesh", 21)
println(studentModel)
val json = Json.encodeToString(StudentInfo.serializer(), studentModel)
println(json)
}
- Output
StudentInfo(studentName=Ramesh, studentAge=21) //Printing the student model
{"name":"Ramesh","age":21} //Printing the json string
-
Marks this property invisible for the whole serialization process, including serial descriptors. Transient properties should have default values.
-
Model object
@Serializable
data class StudentInfo(
@SerialName("name")
val studentName: String,
@SerialName("age")
val studentAge: Int,
@Transient
val isMale: Boolean = false
)
- Converting the model object to json
fun main() {
val data = StudentInfo("Ramesh", 21)
println(data)
val json = Json.encodeToString(StudentInfo.serializer(), data)
println(json)
}
- Output
// Observe the isMale property is not serialized and printed as string
StudentInfo(studentName=Ramesh, studentAge=21) //Printing the student model
{"name":"Ramesh","age":21} //Printing the json string
- We have used list collection as example, But we can use for many other collections similarly.
@Serializable
data class StudentInfo(
val studentName: String,
val studentAge: Int = 21,
)
fun main() {
val student1 = StudentInfo("Ramesh", 21)
val student2 = StudentInfo("Suresh", 21)
val student3 = StudentInfo("Monica", 21)
val student4 = StudentInfo("Peter", 21)
val student5 = StudentInfo("Antony", 21)
val studentList = listOf(student1,student2,student3,student4,student5)
val studentsSerializer = ListSerializer(StudentInfo.serializer())
val json = Json.encodeToString(studentsSerializer, studentList)
println(json)
}
[{"studentName":"Ramesh"},{"studentName":"Suresh"},{"studentName":"Monica"},{"studentName":"Peter"},{"studentName":"Antony"}]
- Sometimes in a nested model hierarcy, There comes the scenario that one of the property is not initilized.
- A useful property of Kotlinx is if you have nested data classes and haven’t defined any of them with @Serializable, the IDE will give you an error.
- Sometimes its good to have this warning, but in other case it forces the class inferred to be annotated as serializable.
- If you have a field that’s in the data class but not in the API, it simply returns null… OR if you set a default value on it, it will remain that default value.
- This is one of the defining traits of Kotlinx Serialization. With most of the other json parsers, even if you set a default value like with the above code, if name were not to be found in the API, they would be null. In Kotlinx, it defaults back to the default value.
@Serializable
data class StudentInfo(
val studentName: String,
val studentAge: Int = 21,
)
If you feel like support me a coffee for my efforts, I would greatly appreciate it.
Read contribution guidelines for more information regarding contribution.
Feature requests are always welcome, File an issue here.
Support it by clicking the ⭐ button on the upper right of this page. ✌️
This project is licensed under the Apache License 2.0 - see the LICENSE file for details