xref: /aosp_15_r20/external/kotlinx.serialization/guide/example/example-serializer-11.kt (revision 57b5a4a64c534cf7f27ac9427ceab07f3d8ed3d8)
1 // This file was automatically generated from serializers.md by Knit tool. Do not edit.
2 package example.exampleSerializer11
3 
4 import kotlinx.serialization.*
5 import kotlinx.serialization.json.*
6 import kotlinx.serialization.encoding.*
7 import kotlinx.serialization.descriptors.*
8 
9 @Serializable
10 @SerialName("Color")
11 private class ColorSurrogate(val r: Int, val g: Int, val b: Int) {
12     init {
13         require(r in 0..255 && g in 0..255 && b in 0..255)
14     }
15 }
16 
17 object ColorSerializer : KSerializer<Color> {
18     override val descriptor: SerialDescriptor = ColorSurrogate.serializer().descriptor
19 
serializenull20     override fun serialize(encoder: Encoder, value: Color) {
21         val surrogate = ColorSurrogate((value.rgb shr 16) and 0xff, (value.rgb shr 8) and 0xff, value.rgb and 0xff)
22         encoder.encodeSerializableValue(ColorSurrogate.serializer(), surrogate)
23     }
24 
deserializenull25     override fun deserialize(decoder: Decoder): Color {
26         val surrogate = decoder.decodeSerializableValue(ColorSurrogate.serializer())
27         return Color((surrogate.r shl 16) or (surrogate.g shl 8) or surrogate.b)
28     }
29 }
30 
31 @Serializable(with = ColorSerializer::class)
32 class Color(val rgb: Int)
mainnull33 fun main() {
34     val green = Color(0x00ff00)
35     println(Json.encodeToString(green))
36 }
37