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) When we want to use it we need add " annotation to our class.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |