
Ok, and what can we use if we want to use different name for serialization? Like json has an id like "background_color" and we want to map to our backgroundColor field. In this case we do not have to use custom serializer when encode or decode the object. Here are the main features it brings: A new API and multiplatform support for kotlinx-coroutines-test introduce a common solution for writing portable tests with suspending functions.Support for the new Kotlin/Native memory manager makes multithreaded coroutines for Kotlin/Native available out of. Or we want to use it in another data class: data class ViewData(val viewName: String, = ColorAsStringSerializer::class) val backgroundColor: Color, = ColorAsStringSerializer::class) val textColor: Color) Following the release of Kotlin 1.6.0, the 1.6.0 version of the routines library is out. It is much more flexible when we are using it with annotation: = ColorAsStringSerializer::class) class Color(val rgb: Int) Now when you want to use this custom serializer you can use it when you serialize that object: val colorWhite = Color.WHITE val jsonString = Json.encodeToString(ColorAsStringSerializer, colorData) => "FFFFFF" Anyway there are lot cases how and why we want to write a custom serializer. There are lot of reason why we want to write a custom serilizer (like convert to other format or other type). (you can find this example in Kotlinx serialization Github page) In this case we have to create our custom serializer: object ColorAsStringSerializer : KSerializer (white -> "FFFFFF", and black -> "000000" it contains RGB color)

For example when we serialize something like a Color we want to serialize it with hexa string like in CSS. That sounds good, however there are a lot of cases when it is not enough for us. With annotation compiler will generate some code with a default implementation (automatic). :) Every class has a serializer which can identify data type and serializes it. data class Data(val text: String, val age: Int)Īnd after it we can serialize or deserialize Data class val jsonString = Json.encodeToString(data) or val object = codeFromString(jsonString) Declaring functions inside of a sealed class is pretty straightforward.When we want to use it we need add " annotation to our class.
