1 // This file was automatically generated from serializers.md by Knit tool. Do not edit.
2 package example.exampleSerializer12
3
4 import kotlinx.serialization.*
5 import kotlinx.serialization.json.*
6 import kotlinx.serialization.encoding.*
7 import kotlinx.serialization.descriptors.*
8
9 object ColorAsObjectSerializer : KSerializer<Color> {
10
11 override val descriptor: SerialDescriptor =
<lambda>null12 buildClassSerialDescriptor("Color") {
13 element<Int>("r")
14 element<Int>("g")
15 element<Int>("b")
16 }
17
serializenull18 override fun serialize(encoder: Encoder, value: Color) =
19 encoder.encodeStructure(descriptor) {
20 encodeIntElement(descriptor, 0, (value.rgb shr 16) and 0xff)
21 encodeIntElement(descriptor, 1, (value.rgb shr 8) and 0xff)
22 encodeIntElement(descriptor, 2, value.rgb and 0xff)
23 }
24
deserializenull25 override fun deserialize(decoder: Decoder): Color =
26 decoder.decodeStructure(descriptor) {
27 var r = -1
28 var g = -1
29 var b = -1
30 while (true) {
31 when (val index = decodeElementIndex(descriptor)) {
32 0 -> r = decodeIntElement(descriptor, 0)
33 1 -> g = decodeIntElement(descriptor, 1)
34 2 -> b = decodeIntElement(descriptor, 2)
35 CompositeDecoder.DECODE_DONE -> break
36 else -> error("Unexpected index: $index")
37 }
38 }
39 require(r in 0..255 && g in 0..255 && b in 0..255)
40 Color((r shl 16) or (g shl 8) or b)
41 }
42 }
43
44 @Serializable(with = ColorAsObjectSerializer::class)
45 data class Color(val rgb: Int)
46
mainnull47 fun main() {
48 val color = Color(0x00ff00)
49 val string = Json.encodeToString(color)
50 println(string)
51 require(Json.decodeFromString<Color>(string) == color)
52 }
53