Roman Elizarov | 5459c10 | 2020-08-11 12:27:36 +0300 | [diff] [blame] | 1 | // This file was automatically generated from serializers.md by Knit tool. Do not edit. |
| 2 | package example.exampleSerializer09 |
| 3 | |
| 4 | import kotlinx.serialization.* |
| 5 | import kotlinx.serialization.json.* |
| 6 | import kotlinx.serialization.encoding.* |
| 7 | import kotlinx.serialization.descriptors.* |
| 8 | |
| 9 | object ColorAsStringSerializer : KSerializer<Color> { |
| 10 | override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Color", PrimitiveKind.STRING) |
| 11 | |
| 12 | override fun serialize(encoder: Encoder, value: Color) { |
| 13 | val string = value.rgb.toString(16).padStart(6, '0') |
| 14 | encoder.encodeString(string) |
| 15 | } |
| 16 | |
| 17 | override fun deserialize(decoder: Decoder): Color { |
| 18 | val string = decoder.decodeString() |
| 19 | return Color(string.toInt(16)) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | @Serializable(with = ColorAsStringSerializer::class) |
| 24 | data class Color(val rgb: Int) |
| 25 | |
| 26 | @Serializable |
| 27 | data class Settings(val background: Color, val foreground: Color) |
| 28 | |
| 29 | fun main() { |
| 30 | val data = Settings(Color(0xffffff), Color(0)) |
| 31 | val string = Json.encodeToString(data) |
| 32 | println(string) |
| 33 | require(Json.decodeFromString<Settings>(string) == data) |
| 34 | } |