In this section, we will look at the kotlinx.serialization library. This consists of three parts:
- Plugin
- Compiler
- Library
To make a class serializable, we should mark it with the @Serializable annotation:
@Serializable
data class Person(
val id: Int = 0,
val first_name: String,
val last_name: String,
val phones: List<String> = listOf()
)
We can serialize an instance of this class to JSON by using the following code:
fun main(args: Array<String>) {
println(JSON.stringify(Person(first_name = "Igor", last_name = "Kucherenko")))
}
The output looks like this:
{"id":0,"first_name":"Igor","last_name":"Kucherenko","phones":[]}
We can deserialize JSON by using the following code:
val jsonPerson = """{"id":0...