xref: /aosp_15_r20/external/kotlinx.serialization/guide/example/example-json-28.kt (revision 57b5a4a64c534cf7f27ac9427ceab07f3d8ed3d8)
1 // This file was automatically generated from json.md by Knit tool. Do not edit.
2 package example.exampleJson28
3 
4 import kotlinx.serialization.*
5 import kotlinx.serialization.json.*
6 
7 import kotlinx.serialization.descriptors.*
8 import kotlinx.serialization.encoding.*
9 
10 data class UnknownProject(val name: String, val details: JsonObject)
11 
12 object UnknownProjectSerializer : KSerializer<UnknownProject> {
<lambda>null13     override val descriptor: SerialDescriptor = buildClassSerialDescriptor("UnknownProject") {
14         element<String>("name")
15         element<JsonElement>("details")
16     }
17 
deserializenull18     override fun deserialize(decoder: Decoder): UnknownProject {
19         // Cast to JSON-specific interface
20         val jsonInput = decoder as? JsonDecoder ?: error("Can be deserialized only by JSON")
21         // Read the whole content as JSON
22         val json = jsonInput.decodeJsonElement().jsonObject
23         // Extract and remove name property
24         val name = json.getValue("name").jsonPrimitive.content
25         val details = json.toMutableMap()
26         details.remove("name")
27         return UnknownProject(name, JsonObject(details))
28     }
29 
serializenull30     override fun serialize(encoder: Encoder, value: UnknownProject) {
31         error("Serialization is not supported")
32     }
33 }
34 
mainnull35 fun main() {
36     println(Json.decodeFromString(UnknownProjectSerializer, """{"type":"unknown","name":"example","maintainer":"Unknown","license":"Apache 2.0"}"""))
37 }
38