blob: c308b6346e58d890b3a6c0e316a7a6b7afb16dd2 [file] [log] [blame]
Leonid Startsev7a35a2d2023-05-17 12:32:30 +02001// This file was automatically generated from json.md by Knit tool. Do not edit.
2package example.exampleJson26
3
4import kotlinx.serialization.*
5import kotlinx.serialization.json.*
6
7import kotlinx.serialization.descriptors.*
8import kotlinx.serialization.encoding.*
9
Leonid Startsev782b9f32023-07-05 19:18:17 +020010@Serializable(with = ResponseSerializer::class)
11sealed class Response<out T> {
12 data class Ok<out T>(val data: T) : Response<T>()
13 data class Error(val message: String) : Response<Nothing>()
14}
Leonid Startsev7a35a2d2023-05-17 12:32:30 +020015
Leonid Startsev782b9f32023-07-05 19:18:17 +020016class ResponseSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<Response<T>> {
17 override val descriptor: SerialDescriptor = buildSerialDescriptor("Response", PolymorphicKind.SEALED) {
Leonid Startsev77af2c92023-08-22 13:59:49 +020018 element("Ok", dataSerializer.descriptor)
19 element("Error", buildClassSerialDescriptor("Error") {
20 element<String>("message")
Leonid Startsev782b9f32023-07-05 19:18:17 +020021 })
Leonid Startsev7a35a2d2023-05-17 12:32:30 +020022 }
23
Leonid Startsev782b9f32023-07-05 19:18:17 +020024 override fun deserialize(decoder: Decoder): Response<T> {
25 // Decoder -> JsonDecoder
26 require(decoder is JsonDecoder) // this class can be decoded only by Json
27 // JsonDecoder -> JsonElement
28 val element = decoder.decodeJsonElement()
29 // JsonElement -> value
30 if (element is JsonObject && "error" in element)
31 return Response.Error(element["error"]!!.jsonPrimitive.content)
32 return Response.Ok(decoder.json.decodeFromJsonElement(dataSerializer, element))
Leonid Startsev7a35a2d2023-05-17 12:32:30 +020033 }
34
Leonid Startsev782b9f32023-07-05 19:18:17 +020035 override fun serialize(encoder: Encoder, value: Response<T>) {
36 // Encoder -> JsonEncoder
37 require(encoder is JsonEncoder) // This class can be encoded only by Json
38 // value -> JsonElement
39 val element = when (value) {
40 is Response.Ok -> encoder.json.encodeToJsonElement(dataSerializer, value.data)
41 is Response.Error -> buildJsonObject { put("error", value.message) }
42 }
43 // JsonElement -> JsonEncoder
44 encoder.encodeJsonElement(element)
Leonid Startsev7a35a2d2023-05-17 12:32:30 +020045 }
46}
47
Leonid Startsev782b9f32023-07-05 19:18:17 +020048@Serializable
49data class Project(val name: String)
50
Leonid Startsev7a35a2d2023-05-17 12:32:30 +020051fun main() {
Leonid Startsev782b9f32023-07-05 19:18:17 +020052 val responses = listOf(
53 Response.Ok(Project("kotlinx.serialization")),
54 Response.Error("Not found")
55 )
56 val string = Json.encodeToString(responses)
57 println(string)
58 println(Json.decodeFromString<List<Response<Project>>>(string))
Leonid Startsev7a35a2d2023-05-17 12:32:30 +020059}